Oni*_*adu 2 c linked-list head nodes
我在c中创建了一个链表结构
struct node{
int value;
struct node* next;
};
Run Code Online (Sandbox Code Playgroud)
在列表开头添加节点的方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
我创建了一个列表(malloc和所有东西),然后调用这个方法,它在方法中添加了新节点,但是当我回到我的main时,我的旧列表保持不变.使用DDD调试器检查所有内容.这怎么可能?我无法更改方法签名,所以必须这样做.
节点指针无法以这种方式更改为函数.在函数中,您可以更改指针的内容而不是指针的地址.要做,你必须传递指针指针struct node **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;
}
Run Code Online (Sandbox Code Playgroud)
或者你可以这样做
struct node * addFirst(struct node *list, int value){
struct node *new_node = (struct node*) malloc (sizeof (struct node));
new_node->value = value;
new_node->next = list;
return new_node;
}
Run Code Online (Sandbox Code Playgroud)
在你的鳕鱼中,你可以在调用此功能后获得头部
head = addfirst(head,45);
Run Code Online (Sandbox Code Playgroud)
如果你真的需要这样做,你必须重新投射指针.像这样的东西:
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;
}
Run Code Online (Sandbox Code Playgroud)