我在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;
}
然后在主函数中,只添加了929。
//testing addNodeBottom function
addNodeBottom(929, head);
addNodeBottom(98, head);
addNodeBottom(122, head);
addNodeBottom(11, head);
addNodeBottom(1034, head);
current->next = newNode;
之后执行break;
。 - samplebiasnode
提供结构定义并添加新行吗?另外,你是如何知道这是这种情况的? - Mr. Shickadance