[英]How does the double pointers work for a linked list implementation?
The following code works fine:以下代码工作正常:
#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);
}
But when I try that bellow, nothing happens and head remains nullptr along with all the operations.但是当我尝试以下操作时,什么都没有发生,并且 head 与所有操作一起保持为 nullptr。 All I did was that I passed single pointers to function instead of double pointers:
我所做的只是将单指针传递给 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);
}
I don't understand why do I need double pointers to make it work?我不明白为什么我需要双指针才能使其工作? Is the second program only sending a copy of head to the functions and nothing more?
第二个程序是否仅向函数发送 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);
}
}
you can't change the value of pointer head
by push_back
in main
function.您不能通过
main
function 中的push_back
更改指针head
的值。 We can change a object by passing its pointer or reference to another function, but not by passing itself!我们可以通过传递它的指针或对另一个 function 的引用来更改 object,但不能通过传递自身! So each time
head = new Node(data);
所以每次
head = new Node(data);
(try to change head
) actually not change head
in the function which called push back()
and caused memory overflow (尝试更换
head
)实际上没有在调用push back()
并导致 memory 溢出的 function 中更换head
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.