【问题标题】:How does the double pointers work for a linked list implementation?双指针如何用于链表实现?
【发布时间】: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 * &amp;head) 比双指针 imo 更清晰。
  • 如果你想要一个函数来修改一个东西,你需要给它一个指向那个东西的指针(或引用),不管这个东西的类型。恰好是指针的东西并没有什么特别之处。
  • 由于您不想 Print 修改 int main() 中的 head 您应该使用 void Print(Node *head){ 来修改 main 中的头指针的函数,您希望通过引用传递指针. void push_back(Node* &amp;head, int data){

标签: c++ pointers linked-list reference


【解决方案1】:
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 函数中通过push_back 更改指针head 的值。我们可以通过将对象的指针或引用传递给另一个函数来更改对象,但不能通过传递自身!所以每次head = new Node(data);(尝试更改head)实际上并没有在调用push back()的函数中更改head并导致内存溢出

【讨论】:

  • 这确实有帮助,但它只对对象有效,还是对每种类型的指针有效?
  • 我的荣幸。当然每种类型的指针。对不起,我的表达不是很准确。我不是以英语为母语的人。
猜你喜欢
  • 2013-10-29
  • 1970-01-01
  • 2013-04-28
  • 2015-09-09
  • 1970-01-01
  • 2012-04-20
  • 2012-01-01
  • 1970-01-01
  • 2015-07-16
相关资源
最近更新 更多