什么是一个链表添加节点时,使用双指针的原因是什么? [英] What is the reason for using a double pointer when adding a node in a linked list?

查看:140
本文介绍了什么是一个链表添加节点时,使用双指针的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面两个两个code实施例在一个链表的顶部添加一个节点。
但是,尽管第一code示例使用了双指针第二code示例使用一个单一的指针

The two code examples below both add a node at the top of a linked list. But whereas the first code example uses a double pointer the second code example uses a single pointer

code例子1:

struct node* push(struct node **head, int data)
{
        struct node* newnode = malloc(sizeof(struct node));
        newnode->data = data;
        newnode->next = *head;
        return newnode;
}

push(&head,1);

code例2:

struct node* push(struct node *head, int data)
{
        struct node* newnode = malloc(sizeof(struct node));
        newnode->data = data;
        newnode->next = head;
        return newnode;
}

push(head,1)

两种方法的效果。然而,很多使用链表方案使用双指针增加一个新节点。我知道一个双指针是什么。但是,如果一个单一的指针就足够添加一个新的节点,为什么做了很多的实现依赖于双指针?

Both strategies work. However, a lot of programs that use a linked list use a double pointer to add a new node. I know what a double pointer is. But if a single pointer would be sufficient to add a new node why do a lot of implementations rely on double pointers?

是否有任何情况下,一个指针不工作,所以我们需要去一个双指针?

Is there any case in which a single pointer does not work so we need to go for a double pointer?

推荐答案

某些实现一个指针传递给指针参数允许改变头指针,而不是直接返回新的。因此,你可以写:

Some implementations pass a pointer to pointer parameter to allow changing the head pointer directly instead of returning the new one. Thus you could write:

// note that there's no return value: it's not needed
void push(struct node** head, int data)
{
    struct node* newnode = malloc(sizeof(struct node));
    newnode->data=data;
    newnode->next=*head;
    *head = newnode; // *head stores the newnode in the head
}

// and call like this:
push(&head,1);

这并不需要一个指向头指针的实现必须返回新头,来电者是负责更新它本身:

The implementation that doesn't take a pointer to the head pointer must return the new head, and the caller is responsible for updating it itself:

struct node* push(struct node* head, int data)
{
    struct node* newnode = malloc(sizeof(struct node));
    newnode->data=data;
    newnode->next=head;
    return newnode;
}

// note the assignment of the result to the head pointer
head = push(head,1);

如果调用此函数的时候,你会泄漏你使用malloc分配节点,你不这样做分配和头指针总是指向同一个节点。

If you don't do this assignment when calling this function, you will be leaking the nodes you allocate with malloc, and the head pointer will always point to the same node.

的优势应该清楚了吧:与第二,如果主叫方忘记将返回的节点头指针,不好的事情会发生。

The advantage should be clear now: with the second, if the caller forgets to assign the returned node to the head pointer, bad things will happen.

这篇关于什么是一个链表添加节点时,使用双指针的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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