我正在关注关于链表的斯坦福计算机科学教育图书馆教程。我正在尝试将一个新列表添加到我的链接列表的前面,但根据我从下面定义的 Length 函数获得的打印输出,它无法正常工作。
#include <stdio.h>
#include <stdlib.h>
//build new struct for node
//node has value and points to next node
struct node{
int value;
struct node *next;
};
//declare a new struct node that contains 3 nodes (head, middle, tail)
struct node *Build123(){
struct node *head, *middle, *tail = NULL;
head = malloc(sizeof(struct node));
middle = malloc(sizeof(struct node));
tail = malloc(sizeof(struct node));
head->value = 3;
head->next = middle;
middle->value = 5;
middle->next = tail;
tail->value = 9;
tail->next = NULL;
return head;
};
//declare a function Length and variable counter to calculate size of list
int Length(struct node *head) {
int count = 0;
struct node *iterator = head;
while (iterator != NULL) {
count++;
iterator = iterator->next;
}
return count;
}
//declare function Push to add new lists that would be added to the front
void Push (struct node **headRef, int value){
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->value = value;
newNode->next = *headRef;
}
int main(){
//instantiate the 3 element linked list named beast
struct node *beast = Build123();
//add 2 elements to the front of the linked list via pass by reference
Push(&beast, 6);
Push(&beast, 12);
//calculate length of linked list after elements have been added
int len = Length(beast);
//print length of linked list to screen
printf("%d\n",len);
return 0;
}
当我期望收到 5
时,我得到了 3
。你能帮我找到代码中阻止我获得我期望的值的错误吗?尽管进行了很多修补,我还是无法弄清楚为什么。谢谢!
最佳答案
问题是,当您执行类似Push(&beast, 6);
的操作时,beast
指向的内容不会被函数Push 更改。尽管 Push 向链表添加了更多元素,但当您稍后在 beast 上调用 Length 时,它会在 beast 开始时最初拥有的同一节点上调用它 - 因此它完全不知道额外添加的节点。
在 Push() 结束时,你需要这样做:
*headRef = newNode;
这样 beast
就会正确指向列表的新起点。
关于c - 在C中将元素添加到链表的前面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15893084/