【发布时间】:2020-07-19 19:17:40
【问题描述】:
以下代码可以正常工作:
#include <iostream>
using namespace std;
struct Node{
int data;
struct Node *next;
Node(int data, Node *next = nullptr){
this->data = data;
this->next = next;
}
};
void push_back(Node **head, int data){
if(*head == nullptr){
*head = new Node(data);
}
else{
Node *current = *head;
while(current->next != nullptr){
current = current->next;
}
current->next = new Node(data);
}
}
void Print(Node **head){
Node *current = *head;
while(current != nullptr){
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
int main(){
Node *head = nullptr;
push_back(&head, 5);
push_back(&head, 2);
push_back(&head, 1);
push_back(&head, -7);
Print(&head);
}
但是当我尝试以下操作时,什么都没有发生,并且 head 与所有操作一起保持为 nullptr。 我所做的只是将单指针而不是双指针传递给函数:
#include <iostream>
using namespace std;
struct Node{
int data;
struct Node *next;
Node(int data, Node *next = nullptr){
this->data = data;
this->next = next;
}
};
void push_back(Node *head, int data){
if(head == nullptr){
head = new Node(data);
}
else{
Node *current = head;
while(current->next != nullptr){
current = current->next;
}
current->next = new Node(data);
}
}
void Print(Node *head){
Node *current = head;
while(current != nullptr){
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
int main(){
Node *head = nullptr;
push_back(head, 5);
push_back(head, 2);
push_back(head, 1);
push_back(head, -7);
Print(head);
}
我不明白为什么我需要双指针才能使其工作? 第二个程序是否只向函数发送一个 head 的副本,仅此而已?
【问题讨论】:
-
是的,基本上就是这样。
void Print(Node *head)只有一个指向单个Node的指针,但不“知道”main中的变量。在 C++ 中,void Print(Node * &head)比双指针 imo 更清晰。 -
如果你想要一个函数来修改一个东西,你需要给它一个指向那个东西的指针(或引用),不管这个东西的类型。恰好是指针的东西并没有什么特别之处。
-
由于您不想 Print 修改
int main()中的head您应该使用void Print(Node *head){来修改 main 中的头指针的函数,您希望通过引用传递指针.void push_back(Node* &head, int data){
标签: c++ pointers linked-list reference