我正在关注链接列表的Stanford CS Ed Library教程。我试图在我的链接列表的前面添加一个新列表,并且根据我从下面定义的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;
}
当我希望收到3
时,我会收到5
。你能不能帮助我找到代码中的错误,阻止我获得我期望的价值?我无法弄清楚为什么尽管有很多修修补补。谢谢!
答案 0 :(得分:4)
问题在于,当您执行Push(&beast, 6);
之类的操作时,beast
指向的内容未被函数Push更改。尽管Push会向链表中添加更多元素,但是当你稍后在野兽上调用Length时,它会在最初与野兽一样的节点上调用它 - 所以它完全不知道额外的添加节点。
在Push()结束时,你需要这样做:
*headRef = newNode;
这样beast
将正确指向列表的新开头。
答案 1 :(得分:3)
您不会修改headRef
函数中的Push
,因此列表的头部实际上从未发生变化。 beast
始终指向创建它指向的原始节点。添加以下行:
*headRef = newNode;
在Push()
中,您将被设置。
答案 2 :(得分:1)
在push()
方法结束时,您必须添加:
*headRef = newNode
这是因为headRef
应始终指向链接列表中的第一个节点。