gpt4 book ai didi

c - 使用指向指针的指针删除结构节点

转载 作者:太空宇宙 更新时间:2023-11-04 02:27:31 25 4
gpt4 key购买 nike

假设我有一个链表,下一个函数从链表中删除struct node

struct list **lpp;
for (lpp = &list; *lpp != NULL; lpp = &(*lpp)->next)
{
if ((*lpp)->item == i)
{
*lpp = (*lpp)->next;
break;
}
}

请解释一下:

  1. lpp = &(*lpp)->next, can I write it as lpp = lpp->next, is this not the same?
  2. *lpp = (*lpp)->next

最重要的是,我没有看到这个函数如何从列表中删除结构节点

最佳答案

lpp 指向列表的第一个元素或某个元素的 next 指针。

通过 *lpp = (*lpp)->next 你将它直接写入内存。例如。考虑一个列表

| el0 | -> | el1 | -> | el2 | -> NULL
list list->next

list 从你的代码点到 el0lpp = &list

现在有两种情况:

  • el0 匹配 i: --> list 变成 |el0|.next el1。运行这个函数后,你有
    | el1 | -> | el2 | -> 空
    列表列表->下一个
  • elX 匹配 i(带有 X>0):lpp&el_{X- 1}.next*lpp = ...,这个 .next 将指向 elX.next。例如。假设 el1 匹配,你得到
    | el0 | -> | el2 | -> 空

lpp = &(*lpp)->next 用于获取对next 的引用。一个简单的 lpp = lpp->next 是不够的,因为它们是不同的类型。当您在 lpp->next 上工作时,*lpp 类似于 *lpp->next,它将取消引用下一个元素的内容。

单列表操作

虽然与这个问题无关但是由于其他讨论,一些更多的代码......

假设数据结构如下

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

在实际代码中,data 不会是该节点的成员,但 struct node 将是另一个对象中的混合,类似于 container_of 用于访问它。但是对于这道题,保持如上...

我们可以定义一些函数,比如

void slist_add(struct node *node, struct node *root)
{
node->next = root->next;
root->next = node;
}

void slist_remove(struct node **node)
{
if (node)
*node = (*node)->next;
}

struct node **slist_search(struct node *root, int key)
{
struct node **ptr;

for (ptr = &root->next; *ptr; ptr = &(*ptr)->next) {
if ((*ptr)->data == key)
return ptr;
}

return NULL;
}

然后,我们使用一个空的结构节点作为 anchor :

int main(void)
{
struct node head = { .next = NULL };

/* add a node */
{
struct node *n = malloc(sizeof *n);
n->data = 23;

slist_add(n, &head);
}

/* add a node */
{
struct node *n = malloc(sizeof *n);
n->data = 42;

slist_add(n, &head);
}

/* verify our expectations... */
assert(head.next != NULL);
assert(head.next->data == 42);

assert(head.next->next != NULL);
assert(head.next->next->data == 23);
assert(head.next->next->next == NULL);

/* remove the node */
{
struct node **ptr = slist_search(&head, 42);

assert(ptr != NULL);
assert(*ptr != NULL);
assert((*ptr)->data == 42);

if (ptr) {
struct node *n = *ptr;
slist_remove(ptr);
free(n);
}
}

/* remove the node */
{
struct node **ptr = slist_search(&head, 23);

assert(ptr != NULL);
assert(*ptr != NULL);
assert((*ptr)->data == 23);

if (ptr) {
struct node *n = *ptr;
slist_remove(ptr);
free(n);
}
}

assert(head.next == NULL);
}

关于c - 使用指向指针的指针删除结构节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48975680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com