简单的链表-C
从C编程中度过了夏天之后,我又重新回到了课程中,并且正在努力追赶,特别是在指针方面。
当前的赋值让我们将程序从数组结构转换为简单的链表。 为了刷新我的记忆,我尝试在一个独立程序中实现它,但遇到了麻烦。
我的代码:
struct node{ int val; struct node *next; }; typedef struct node *item; item newNode(void); //function prototype void main(){ item *cur, *itemList; int i; itemList=NULL; for (i=0; ival=i; cur->next= itemList; } } item newNode(void) { item box; /* the new object to return */ box = (item) malloc (sizeof (struct node)); if (box == NULL) { printf("ERROR: emalloc failed for new Box\n"); exit(0); } /* initialize fields */ box->val=0; return box; }
第一条错误消息来自cur= newBox()
,并声明正在进行来自不兼容指针类型的cur= newBox()
。 我不知道为什么,因为cur是指向节点的指针,而box是一个结构。 不兼容的指针来自哪里?
第一个问题是你做的item *cur, *itemList;
这是一个node**
。 将其更改为item cur, itemList;
得到node*
; 您不需要指向node
的指针,只需指向node
的指针。
另一个问题是你将节点的所有next
指针设置为itemList
而没有在每个循环迭代结束时将itemList
设置为cur
(这将使itemList
指向循环结束时列表的开头)。
你需要一个指针
如果你的typedef是这样的话更清楚:
typedef struct node item;
然后:
item *newNode(void) { item *box; /* the new object to return */ box = (item) malloc (sizeof (struct node)); if (box == NULL) { printf("ERROR: emalloc failed for new Box\n"); exit(0); } /* initialize fields */ box->val=0; return box; }
你也可以在不同的地方调用函数newNode和newBox。
您还需要重置头指针:
for (i=0; i<=10; i++){ cur= newBox(); cur->val=i; cur->next= itemList; itemList = cur; }
在主要你使用item*
是node**
。 只需删除main中声明列表中的*
。
cur
是类型item*
,指向item的指针。 但是newNode(void)
的返回类型是item
。 它们都不兼容。