c++ - 链表头双指针传递

标签 c++ c linked-list reverse double-pointer

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

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

例如: //这是为了反转头指向第一个节点的链表。

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;
}

这很好用。

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

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;
}

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

我错过了什么吗?

谢谢,

最佳答案

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

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

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

int x = 7;
foo(x);
// x is still 7

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

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

int x = 7;
foo(&x);
// x is 5

对您来说,不是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

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

当然在 C++ 中你不会自己实现一个列表,你会使用 std::list

关于c++ - 链表头双指针传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3313233/

相关文章:

c - 删除链表尾部 : Why a specific approach won't work

java - 确定对象的类型

c++ - 具有个人比较功能的 std::set 具有相同的值

c - 我无法让循​​环循环 20 次并要求输入 1 到 6 之间的数字。任何人都可以看到我编码错误的地方吗?

c - 在 malloc 实现中维护空闲列表

使用 mingw64 编译一个 mpi 项目

c++ - 使用模板 C++ 的链表实现中未解析的外部符号

C++ - 如何调用创建者类/对象

c++ - 在 Qt 5 中重用现有的 QDirIterator

c++ - glColor() 未在此范围内声明