|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 a327904410 于 2021-11-15 20:10 编辑
- #include<stdio.h>
- #include<stdlib.h>
- typedef int ElemType;
- typedef struct node {
- ElemType data;
- struct node* next;
- }Node;
- int InitNode(Node* L) {
- L = (Node*)malloc(sizeof(Node));
- L->next = L;
- return 1;
- }
- // 尾插
- int InsNode(Node* L, ElemType x, int i) {
- int j = 1;
- Node* pre = L, * p = pre->next, * s;
- if (i <= 0)
- return 0;
- while (p != L && j < i) {
- j++;
- pre = p; p = p->next;
- }
- if (p == L && i > j + 1)
- return 0;
- else {
- s = (Node*)malloc(sizeof(Node));
- s->data = x;
- s->next = pre->next;
- pre->next = s;
- return 1;
- }
- }
- //输出线性表运算算法
- void DispList(Node* L) {
- Node* p = L->next;
- while (p != L) {
- printf("%d ", p->data);
- p = p->next;
- }
- printf("\n");
- }
- int main() {
- int i;
- Node L;
- InitNode(&L);
- InsNode(&L, 1, 1);
- InsNode(&L, 3, 2);
- InsNode(&L, 1, 3);
- InsNode(&L, 5, 4);
- InsNode(&L, 4, 5);
- InsNode(&L, 2, 6);
- DispList(&L);
- return 0;
- }
复制代码
本帖最后由 jhq999 于 2021-11-16 15:10 编辑
明白了
- int InitNode(Node* L) {
- //L = (Node*)malloc(sizeof(Node));//画蛇添足,L已经有实例了不需要申请内存,
- //申请了新内存空间只不过是让形参的指针指向新内存,形参和实参再也没有关系
- L->next = L;
- return 1;
- }
复制代码
或者
- #include<stdio.h>
- #include<stdlib.h>
- typedef int ElemType;
- typedef struct node {
- ElemType data;
- struct node* next;
- }Node;
- int InitNode(Node**L) {//////////////
- *L = (Node*)malloc(sizeof(Node));
- (*L)->next = *L;
- return 1;
- }
- // 尾插
- int InsNode(Node* L, ElemType x, int i) {
- int j = 1;
- Node* pre = L, * p = pre->next, * s;
- if (i <= 0)
- return 0;
- while (p != L && j < i) {
- j++;
- pre = p; p = p->next;
- }
- if (p == L && i > j + 1)
- return 0;
- else {
- s = (Node*)malloc(sizeof(Node));
- s->data = x;
- s->next = pre->next;
- pre->next = s;
- return 1;
- }
- }
- //输出线性表运算算法
- void DispList(Node* L) {
- Node* p = L->next;
- while (p != L) {
- printf("%d ", p->data);
- p = p->next;
- }
- printf("\n");
- }
- int main() {
- int i;
- Node *L=NULL;/////////
- InitNode(&L);//////////
- InsNode(L, 1, 1);
- InsNode(L, 3, 2);
- InsNode(L, 1, 3);
- InsNode(L, 5, 4);
- InsNode(L, 4, 5);
- InsNode(L, 2, 6);
- DispList(L);
- return 0;
- }
复制代码
|
|