下加入节点链表头 [英] C adding node to head of linked list

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

问题描述

我已经创建了一个在C链表结构

I have created a linked list struct in c

struct node{
   int value;
   struct node* next;
};

的方法来在列表的开头添加节点

a method to add a node at the start of the list :

void addFirst(struct node *list, int value){
    struct node *new_node = (struct node*) malloc (sizeof (struct node));
    new_node->value = value;
    new_node->next = list;
    list = new_node;
   }

我创建一个列表(malloc和一切),然后调用该方法,它添加方法中新的节点,但是当我回到我的主我的老名单保持不变。使用DDD调试器来检查一切。这怎么可能?我不能改变方法签名所以它必须这样做。

I create a list (malloc and everything), then call this method, it adds the new node inside the method but when i get back to my main my old list remains unchanged. Using DDD debugger to check everything. How is this possible? I am not able to change the method signature so it has to be done like this.

推荐答案

如果你真的需要做这种方式,你必须重新转换指针。事情是这样的:

If you really need to do it this way, you have to re-cast the pointer. Something like this:

struct node *my_list = null;
addFirst((struct node *)&my_list, 123);

void addFirst(struct node *list, int value){
    struct node **real_list = (struct node **)list;
    struct node *new_node = (struct node*) malloc (sizeof (struct node));
    new_node->value = value;
    new_node->next = *real_list;
    *real_list = new_node;

}

这篇关于下加入节点链表头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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