我有一个链表结构,我想将一个节点(另一个结构)指针传递给一个函数(该节点是链表的一部分,但我将节点单独传递给删除器函数
我希望它将下一个节点数据复制到自身中(覆盖其数据),并删除下一个节点,从而删除自身(这部分正在工作)。
我让它检查传递的节点是否是列表中的最后一个节点,如果是,则删除自身。
我不知道如何从堆栈中删除结构(我知道我可以使用堆内存对其进行 malloc() 和 free() )。
#include <stdlib.h>
#include <stdio.h>
typedef struct {
int data;
struct node * next;
}node;
typedef struct {
struct node * head;
}linked_list;
void print_list(linked_list * list) {
node *current = list->head;
while (current) {
printf("Current node has %d\n",current->data);
current = current->next;
}
}
void delete_node(node * n) {
node * next = n->next;
if (next) {
n->data = next->data;
n->next = next->next;
}
else {
*n = NULL; /*This of course won't compile because assigning void* (null) to node variable
but if i make n point to NULL, nothing will happen because i'm inside a function
and the pointer is duplicated (the passed pointer will still work) */
}
}
void main(){
node first;
node second;
first.data = 1;
first.next = &second;
second.data = 2;
second.next = NULL;
linked_list l;
l.head = &first;
print_list(&l);
delete_node(&second);
print_list(&l);
}
正如其他人所说,你不能.
如果您希望能够存储两个分配的(通过malloc
)和列表中的非分配(静态或自动)存储对象,并具有从列表中删除对象并释放它们的“删除”功能,您需要将一个标志存储为每个列表成员的一部分,指示它是否在分配的存储中或不,并且只释放那些是的。
另请注意,如果自动存储结构的生命周期在您将其从列表中删除之前就结束了,您将遇到大麻烦!如果处理这个问题让您感到困惑,那么您可能会更好地使用分配的存储(malloc
) 对于所有列表成员。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)