[英]How does the double pointers work for a linked list implementation?
以下代码工作正常:
#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。 我所做的只是将单指针传递给 function 而不是双指针:
#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 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);
}
}
您不能通过main
function 中的push_back
更改指针head
的值。 我们可以通过传递它的指针或对另一个 function 的引用来更改 object,但不能通过传递自身! 所以每次head = new Node(data);
(尝试更换head
)实际上没有在调用push back()
并导致 memory 溢出的 function 中更换head
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.