当插入到链表的头部时,与指针混淆

Confusion with pointers whilst inserting to the head of a linked list

本文关键字:指针 头部 插入 链表      更新时间:2023-10-16

我正在处理一个链表示例。然而,我目前无法理解head_insert方法。谁能再解释一下吗?谢谢你。

#include <iostream>
using namespace std;
struct node_ll
{
    int payload;
    node_ll* next;  // pointer to the next node
};
void head_insert(node_ll** list, int pload)
{
    node_ll* temp = new node_ll;//Declare temp, a pointer to a node.
    temp->payload = pload;//Set the payload of the struct at the address of temp to pload.
    temp->next = *list;//Set the next of the struct at the address of temp to the pointer to the old head of the list.
    *list = temp;//Set the pointer to the old head of the list to the pointer to the temp node.
    //Why doesnt the temp->next = temp?
};
void print_ll(node_ll** list)
{
    node_ll* temp;
    temp = *list;
    while (temp) // != NULL
    {
        cout << temp->payload << 'n';
        temp = temp->next;
    };
}
int main()
{
    node_ll* alist = NULL;  
    cout << "Empty list a to startn";
    head_insert(&alist, 2); 
    head_insert(&alist, 4);
    head_insert(&alist, 6);
    cout << "List a after head insertion of 2,4,6 is n";
    print_ll(&alist);
    cout << 'n';
    system("PAUSE");
    return 0;
}

我的困惑在评论中详细说明了。如果我有

一行
temp->next = *list;
*list = temp;

为什么我新创建的节点在next中没有指向它自己的地址?

//Declare temp, a pointer to a node.

。"创建一个新节点,让temp为该节点的地址。"

//Set the payload of the struct at the address of temp to pload.

。设置地址为 temp的结构体payload为加载。这可能就是你的意思,但你真的需要精确地处理这些事情。无论如何,这是在填充我们刚刚创建的新节点的payload

//Set the next of the struct at the address of temp to the pointer to the old head of the list.

同样……"将地址为 temp的结构体next设置为 list的旧头的地址。"

//Set the pointer to the old head of the list to the pointer to the temp node.

小心。事情是这样的:"旧列表头的地址"是一个,而不是一个变量。它可以存在于内存的多个位置,就像数字4可以存储在内存的多个位置一样。

给函数一个node_ll**,即一个(node_ll*)*——一个指向node_ll*的指针。具体来说,当我们从main调用函数时,我们给了它一个指针,指向当前调用main 中的变量a_list

因此,当我们执行*list =时,我们正在向写入内存位置-实际上,替换了a_list变量。像这样处理内存地址允许我们模拟"引用传递"并改变来自调用者的变量的值(我们不能仅仅从参数中访问这些值,因为我们得到了一个副本;而且我们不能把它们作为全局变量来访问,因为它们不是全局变量。
//Why doesnt the temp->next = temp?

为什么呢?代码从上到下运行(不管控制结构如何)。temp->next被设置为旧的列表头,之前我们设置了新的列表头。

看起来你期望temp->next改变只是因为,在这个过程中,它恰好指向列表的旧头,然后我们改变了一个变量,它也恰好具有相同的值——即,指向列表的旧头。但它们显然是独立的变量。如果我写a = 4; a *= 3,值4不会改变;变量a可以。指针也是如此;它们只是另一种价值。

这是令人困惑的代码。

list是指向指向节点的指针的指针。*list = temp不是改变任何节点,它改变了传入的指针,所以它指向插入的节点。

head_insert函数中,新的Node被添加到开头。这个新节点将成为链表的头

temp->next = *list;//Store pointer to earlier head as the next node
*list = temp;  // Make pointer new node as the head node
在你的代码中,双指针作为参数传递给函数。例如,如果A是你的指针头节点,那么地址B包含A作为参数传递到你的函数。