暑假结束 C 编程之后,我又回到了类里面,并努力 catch 进度,尤其是在指针方面。
当前的作业要求我们将程序从数组结构转换为简单的链表。为了刷新我的内存,我尝试在一个独立的程序中实现它,但遇到了麻烦。
我的代码:
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; i<=10; i++){
cur= newNode();
cur->val=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 是指向节点的指针,而 box 是一个结构。不兼容指针从何而来?
最佳答案
第一个问题是你做的 item *cur, *itemList;
这是一个 node**
。将其更改为 item cur, itemList;
以获取 node*
;您不需要指向 node
的指针,只需指向 node
的指针即可。
另一个问题是您将节点的所有 next
指针设置为 itemList
而未将 itemList
设置为 cur
在每个循环迭代结束时(这将使 itemList
在循环结束时指向列表的开头)。
关于c - 简单链表-C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7314581/