我正在用 C 实现链表,但我的 addhead 函数无法正常工作。怎么了?



我开始学习C,并尝试实现链表。由于某种原因,我的代码没有运行更正。我的addtailprintlist函数可以正常工作,但我的addhead不能正常工作。

我搞不清楚出了什么问题。这是我迄今为止写的代码:

#include <stdio.h>
int main()
{
typedef struct temp_node{
int data;
struct temp_node * next;
} node;
void addtail(node * head, int taildata){
node * tail = malloc(sizeof(node));
tail->data = taildata;
tail->next = NULL;
node * current = head;
while(current->next != NULL){
current = current->next;
}
current->next = tail;
}
void addhead(node ** head, int headdata){
node * newhead = malloc(sizeof(node));
newhead->data = headdata;
newhead->next = *head;
*head = newhead;
}
void printlist(node * head){
node * current = head;
while(current != NULL){
printf("%dn", current->data);
current = current->next;
}
}
node * head = malloc(sizeof(node));
head->data = 0;
head->next = NULL;
addtail(head, 1);
addtail(head, 2);
addhead(head, 5);
printlist(head);
return 0;
}

当我运行它(https://www.tutorialspoint.com/compile_c_online.php)我得到以下输出:

6299760
1
2

为什么这没有正确地更改列表的标题?

我现在有了另一个:为什么在addtail中我正常地传递列表,它运行得很好,而在addhead中我必须通过引用传递它?

这两种方法都很好。要么将指针传递到如下节点:

addhead(node * head, int headdata)

并这样称呼它:addhead(head,5)

或者将指针传递到指向节点的指针(2D指针):

addhead(node ** head, int headdata)

并通过将指针的引用传递到头(即2D指针)的方式调用它:

addhead(&head,5)

我希望它能有所帮助!

相关内容

最新更新