链接列表-指向头部的单指针或双指针 [英] Linked lists - single or double pointer to the head

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

问题描述

给我们一个任务和一个链表结构:

We are given a task and a struct of linked list:

typedef struct dlistint_s
{
    int n;
    struct dlistint_s *prev;
    struct dlistint_s *next;
} dlistint_t; 

具有以下原型的函数:

dlistint_t *add_dnodeint(dlistint_t **head, const int n);

优点是什么,为什么在创建函数时会使用指向头的双指针?

What are the advantages and why one would be using a double pointer to the head when creating a function?

推荐答案

将指针传递给head指针的原因是,对指针head的任何修改都将在调用方函数中看到,而您没有从您的功能返回头.

The reason to pass pointer to pointer to head is that any modification to the pointer head will be seen in the caller function and you do not have to return head from your function.

例如,考虑以下简单节点:

For example, consider this simple node:

struct Node{
    int data;
    struct Node *next;
};

将节点添加到前面的列表中的功能

A function to add a node to the list at front

struct Node *add_node (struct Node *list, int n){
    struct Node *new_node = malloc(sizeof(struct Node));
    if(new_node == NULL){
        printf("Memory allocation failed\n");
        exit(EXIT_FAILURE);
    }
    new_node->data = n;
    new_node->next = list;
    return new_node;
}

如果我们需要将new_node分配给list而不是返回它,那么我们需要修改上述函数并删除return语句并放置一条语句

If we need to assign the new_node to the list instead of returning it then we need to modify the above function and remove the return statement and put a statement

list = new_node;

但是,那是行不通的!
这是因为在C语言中,像所有参数一样,指针是按值传递的. 这意味着list包含传递给add_node函数的指针值的副本,而不包含传递给该函数本身的指针.
那就是我们需要指针的地方.

But, that will not work!
This is because in C, like all arguments, pointers are passed by value. That means the list contains the copy of the pointer value passed to add_node function and not the pointer passed to this function itself.
That's where we need pointer to pointer.

void add_node (struct Node **list, int n){
    struct Node *new_node = malloc(sizeof(struct Node));
    if(new_node == NULL){
        printf("Memory allocation failed\n");
        exit(EXIT_FAILURE);
    }
    new_node->data = n;
    new_node->next = *list;
    *list = new_node;
} 

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

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