【发布时间】:2021-04-16 09:16:23
【问题描述】:
我是编程新手,目前正试图找出 C 中的链表。我创建了一个简单的列表,其中包含三个节点,其中包含数字 1、2 和 3。
typedef struct Node {
int data;
struct Node* next;
} Node;
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1; // assign data in first node
head->next = second; // Link first node with second node
second->data = 2; // assign data to second node
second->next = third;// Link second node with the third node
third->data = 3; // assign data to third node
third->next = NULL;
}
接下来我想使用 add_and_print 函数将用户输入的值插入到列表的开头
int num;
printf("Enter number to add to beginning of list: ");
scanf(" %d", &num);
add_and_print(num, head);
函数 add_and_print 如下所示:
void add_and_print(int num, Node* head) {
Node* new_node;
new_node = (Node*)malloc(sizeof(struct Node));
new_node->data = num;
new_node->next= head;
head = new_node;
printf("Value inside Function: %d\n", head->data);
}
对于“函数内部的值”,我得到了我之前输入的值,到目前为止一切都很好。但是,在 main 中调用该函数后,我尝试再次打印 head 值
add_and_print(num, head);
printf("Value outside function: %d", head->data);
我得到 1,即应用该函数之前的头部值。当我尝试打印整个列表时,我得到 123。我不明白为什么函数所做的更改没有全局保存。
提前谢谢你:)
【问题讨论】:
-
请阅读linked lists 上的维基百科页面。那里有一个漂亮的身影。然后阅读您的编译器(例如GCC,您可以调用为
gcc -Wall -Wextra -g)和调试器(例如GDB)的文档 -
考虑从
add_and_print函数返回new_node。您可以将此值分配给head...
标签: c linked-list pass-by-reference singly-linked-list function-definition