[英]Singly linked list, why is the list empty (head == NULL)?
我创建了一个单链表:
#include <iostream>
using namespace std;
struct Node{
int data;
Node *next;
};
bool isEmpty(Node *head){
if (head == NULL){
return true;
}
else{
return false;
}
}
void append(Node *head, Node *last, int data){
Node *newNode = new Node;
newNode->data = data;
newNode->next = NULL;
if (isEmpty(head)){
head = newNode;
last= newNode;
}
else{
last->next = newNode;
last= newNode;
}
}
void printList(Node *current){
if (isEmpty(current)){
cout << "List is empty." << endl;
}
else{
int i = 1;
while (current != NULL){
cout << i << ". Node: " << endl;
cout << current->data << endl;
current = current->next;
i++;
}
}
}
void main(){
Node *head = NULL;
Node *last = NULL;
append(head, last, 53);
append(head, last, 5512);
append(head, last, 13);
append(head, last, 522);
append(head, last, 55);
printList(head);
}
当我编译它时,输出是这样的:
清单为空。
但是我不知道为什么。 “ head”获取地址,因此“ head”不应为NULL。 但显然是NULL。 我不知道如何解决这个问题。
您必须记住,默认情况下,函数的参数是按值传递的,这意味着将复制参数值,并且该函数仅适用于副本,而不适用于原始副本。
现在使用append
函数,当您传递head
参数时,指针将被复制到该参数中,并且对该函数内部head
所做的任何更改仅会对该副本进行。
为了使其正常工作,您需要传递通过引用更改的参数 ,例如
void append(Node *&head, Node *&last, int data)
现在head
和last
是对原始指针变量的引用,并且对该变量所做的更改是对原始变量的。
参数head
和last
是通过值传递的,因此它们在函数append
的更改与外部变量无关,它们是独立的。
您需要通过引用或指针指针传递它,例如:
void append(Node *&head, Node *&last, int data) {
在函数中: append(Node *head, Node *tail, int data)
您应该通过参考传递head
和tail
。 在您的方法中,当您分配head = newNode
会将其分配给head
的本地副本,而不是您传递的head
。
传递head和last变量的地址,它将有效。
append(&head, &last, 53);
以及添加功能的变化如下
void append(Node **head, Node **last, int data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.