我在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);
解决方法
这段代码可行. samplebias的答案几乎是正确的,但您需要进行第三次更改:
int addNodeBottom(int val,"Unable to allocate memory for new node\n");
exit(-1);
}
newNode->value = val;
newNode->next = NULL; // Change 1
//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 (true) { // Change 2
if(current->next == NULL)
{
current->next = newNode;
printf("added later\n");
break; // Change 3
}
current = current->next;
};
}
return 0;
}
更改1:newNode-> next必须设置为NULL,因此我们不会在列表末尾插入无效指针.
改变2/3:循环变为无限循环,随着休息跳出;当我们找到最后一个元素.注意while(current-> next!= NULL)如果之前(current-> next == NULL)之前是如何矛盾的.
编辑:关于while循环,这种方式更好:
node *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
printf("added later\n");