链表头双指针传递 [英] Linked list head double pointer passing

查看:128
本文介绍了链表头双指针传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一些书/教程看到了这一点。

I have seen this in some book/ tutorial.

当你的头指针(链表)到一个函数传递,你需要把它作为一个双指针。

When you pass in the head pointer (of linked list) into a function, you need to pass it as a double pointer.

有关如:
//这是反向链接的列表,其中头指向第一个节点。

For eg: // This is to reverse a linked list where head points to first node.

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

这工作得很好。

它也可以当我使用单指针一样,

It also works when I use single pointer like,

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

我试图通过使用头指针打印列表。无论是功能正常工作。

I tried printing the list by using the head pointer. Both the functions work fine.

我缺少的东西吗?

谢谢,

推荐答案

这是非常类似于C code,而不是C ++。

This is very C-like code, not C++.

基本上,当事情是​​按值传递的功能上的数据的一个副本操作

Basically, when something is passed by-value the function operates on a copy of the data:

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

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

在C,代替你传递一个指针变量,可以改变这种方式:

In C, you instead pass a pointer to the variable, and can change it that way:

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

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

有关你,而不是一个 INT 这是一个位* 。 (在一个指针指向由此而来。)

For you, instead of an int it's a digit*. (Resulting in a pointer to pointer.)

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

In C++, references were introduced. A reference is an alias to another object. So you'd do something like this:

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

一个参考一般preferred,因为它强制执行,你实际上是指一个对象,并简化了电话和工作code。

A reference is generally preferred, since it enforces that you actually refer to an object, and simplifies both calling and operating code.

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

Of course in C++ you wouldn't implement a list yourself, you'd use std::list.

这篇关于链表头双指针传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆