链表头双指针传递

Joh*_*hnH 3 c c++ reverse linked-list double-pointer

我在一些书/教程中看到过这个。

当您将(链表的)头指针传递给函数时,您需要将其作为双指针传递。

例如: // 这是反向链表,其中 head 指向第一个节点。

void nReverse(digit **head)
{
    digit *prev=NULL;
    digit *curr=*head;
    digit *next;

    while(curr!=NULL)
    {
        next=curr->next;
        curr->next=prev;
        prev=curr;
        curr=next;
    }
    *head=prev;
    return;
}
Run Code Online (Sandbox Code Playgroud)

这工作正常。

当我使用单指针时它也有效,

void nReverse(digit *head)
{
    digit *prev=NULL;
    digit *curr=head;
    digit *next;

    while(curr!=NULL)
    {
        next=curr->next;
        curr->next=prev;
        prev=curr;
        curr=next;
    }
    head=prev;
    return;
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用头指针打印列表。这两个功能都可以正常工作。

我错过了什么吗?

谢谢,

GMa*_*ckG 5

这是非常类似 C 的代码,而不是 C++。

基本上,当按值传递某些内容时,该函数对数据的副本进行操作:

void foo(int i)
{
    i = 5; // copy is set to 5
}

int x = 7;
foo(x);
// x is still 7
Run Code Online (Sandbox Code Playgroud)

在 C 中,您改为传递一个指向变量的指针,并可以通过这种方式更改它:

void foo(int* i)
{
    *i = 5; // whatever i points to is set to 5
}

int x = 7;
foo(&x);
// x is 5
Run Code Online (Sandbox Code Playgroud)

对你来说,int它不是一个,而是一个digit*. (导致指向指针的指针。)


在 C++ 中,引入了引用。引用是另一个对象的别名。所以你会做这样的事情:

void foo(int& i) // i is an alias to another value
{
    i = 5; // x is set to 5
}

int x = 7;
foo(x); // pass x as alias, not address of x.
// x is 5
Run Code Online (Sandbox Code Playgroud)

引用通常是首选,因为它强制您实际引用一个对象,并简化调用和操作代码。

当然,在 C++ 中,您不会自己实现列表,而是使用std::list.