当节点通过函数传递并被接受为双指针时,如何使用双指针查找节点中的值?

How to find the value in a node using a double pointer when that node is passed through a function and accepted as a double pointer?

伙计们,我正在拼命学习如何操作链表,但我遇到了困难。我无法理解大多数在线教程,而且它们对我来说似乎都不直观。我已经成功地尝试使用双指针在链表的开头附加一个节点,但是这个双指针的性质并不像我想象的那样。请参考我下面的代码:

#include <iostream>
using namespace std;

class node{ 
public:
    int value;
    node* next;
};
void push2front(node** ptr, int n) //a node pointer is now equal to the address of the head node
{
    cout<<"ptr: "<<ptr<<endl;
    cout<<"*ptr: "<<*ptr<<endl;
    node* new_node = new node(); //create a new head node
    new_node->value = n;
    new_node->next = *ptr;
    *ptr = new_node;
    return;
}

int main() {
    
    node* head = new node();
    node* second = new node();
    node* third = new node();
    int input = 54;
    head->value = 1; 
    head -> next = second; 
    second->value = 2;
    second->next = third;
    third->value = 3;
    third->next = NULL;
    cout<<"head: "<<head<<endl;//address of the data member value of head
    cout<<"&head->value: "<<&head->value<<endl;//address of the value data member of node head
    cout<<"&head: "<<&head<<endl;//address of the head node itself
    cout<<"head->next: "<<head->next<<endl;//address of the next node after head
    cout<<second<<" "; //address of the data member of 2nd node
    cout<<&second->value<<" ";//address of the data member of 2nd node
    cout<<&second<<endl;//address of the 2nd node itself
    push2front(&head, input); //pass the address of the actual head node as well as the user inputted integer
    while (head!=NULL)
    {
        cout<<head->value<<" ";
        head = head->next;

    }
    return 0;
}

这个程序的输出如下:

head: 0x921520
&head->value: 0x921520
&head: 0x7bfe08
head->next: 0x921540
0x921540 0x921540 0x7bfe00
ptr: 0x7bfe08
*ptr: 0x921520
54 1 2 3

我在程序中放置了很多cout,看看程序运行时会发生什么。一切都很好,很花哨,直到我调用 push2front() 函数的那一刻。这是我的问题:

1.) 当我认为 &head->value or 只是 head 是值数据成员的地址时,我是否正确头节点的?因为根据我的 cout 显示,情况似乎是这样。

2.) 那么这是否意味着 &head 是节点的实际地址?

3.)我一直以为任意节点的next部分指向它旁边节点的ACTUAL地址?所以基本上我认为 head->next == &second?但似乎(根据 cout)节点显然指向值数据成员的地址 另一个节点?

4.) 如果 head: 0x91520 == ptr: 0x91520 为什么 head->value 有效而 *ptr->value 无效?

  1. head包含第一个节点的地址。即该节点占用内存的起始地址。这也是该节点的 value 成员的地址,因为该节点及其 value 成员在同一位置开始。

  2. head是一个指针,也就是一个变量。 &head 是那个指针的地址。 指向事物与指向包含事物地址的变量不同。

  3. 是的,如果链表构造正确,任何节点的next部分都指向下一个节点,也就是说它包含了下一个节点的实际地址。所以head->next == second,这是第二个节点的地址,也是第二个节点的value成员的地址。 不是 head-next == &second 的情况,因为 second 是一个根本不属于列表的指针。

  4. (*ptr)->value 有效; *ptr->value 没有。指针运算符 (->) 优先于解引用运算符 (*),因此当您尝试使用 *ptr->value 时,编译器会将其视为 *(ptr->value) 并报错 ptr->value 是什么意思?ptr 是指向指针的指针,而不是指向具有成员的事物的指针。"