【发布时间】:2011-08-13 10:38:23
【问题描述】:
我在 C 中插入链表的方法遇到了一些问题。它似乎只在列表的开头添加。我做的任何其他插入都失败了。而且这个 CodeBlocks 调试器很难理解,我还是不明白。它从来没有给我价值,只是内存中的地址。无论如何,这是我的职责。你看到它失败的任何原因吗?
/* function to add a new node at the end of the list */
int addNodeBottom(int val, node *head){
//create new node
node *newNode = (node*)malloc(sizeof(node));
if(newNode == NULL){
fprintf(stderr, "Unable to allocate memory for new node\n");
exit(-1);
}
newNode->value = val;
//check for first insertion
if(head->next == NULL){
head->next = newNode;
printf("added at beginning\n");
}
else
{
//else loop through the list and find the last
//node, insert next to it
node *current = head;
while(current->next != NULL)
{
if(current->next == NULL)
{
current->next = newNode;
printf("added later\n");
}
current = current->next;
}
}
return 0;
}
然后在 main 中,只添加了 929。
//testing addNodeBottom function
addNodeBottom(929, head);
addNodeBottom(98, head);
addNodeBottom(122, head);
addNodeBottom(11, head);
addNodeBottom(1034, head);
【问题讨论】:
-
如果我将 newNode->next 设置为 NULL,它仍然只插入第一个
-
在
current->next = newNode;之后执行break; -
你能用
node的结构定义和新行更新代码吗?还有,你怎么知道是这样的? -
您还可以保留一个尾指针,以使您在列表末尾的插入变得简单,而不必遍历列表。
-
+1 同意,保持尾指针追加 O(1)
标签: c insert linked-list binary-tree