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

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

问题描述

下面的两个代码示例都在链表的顶部添加了一个节点.但是第一个代码示例使用双指针,第二个代码示例使用单指针

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

代码示例 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);

代码示例 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);

不带head指针的实现必须返回新的head,调用者自己负责更新:

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天全站免登陆