从C链接列表中删除(指向指针的指针)

时间:2016-11-22 01:04:19

标签: c pointers data-structures

我在C语言中找到了以下代码片段,它从列表中删除了一个元素

void
remove_ll(struct link_list **head, int key)
{
        struct link_list **cur;
        for(cur = head; *cur; ) {
                struct link_list *entry = *cur;
                if (entry->key == key) {
                        *cur = entry->next;
                        free(entry);
                } else {
                        cur = &entry->next;
                }
        }
}

我想了解它是如何运作的。

这是我的想法。

List example:

     0x1f7d018               0x1f7d038              0x1f7d078
+++++++++++++++++++     +++++++++++++++++++     +++++++++++++++++++
|0x2174010:       |     |0x1f7d070:       |     |0x1f7d090:       |
|key = 10         |     |key = 34         |     |key = 90         |
|&next = 0x1f7d038|++++>|&next = 0x1f7d078|++++>|&next = NULL     |
|                 |     |                 |     |                 |
+++++++++++++++++++     +++++++++++++++++++     +++++++++++++++++++

After deleting the value 34

     0x1f7d018               0x1f7d038
+++++++++++++++++++     +++++++++++++++++++
|0x2174010:       |     |0x1f7d090:       |
|key = 10         |     |key = 90         |
|&next = 0x1f7d038|++++>|&next = NULL     |
|                 |     |                 |
+++++++++++++++++++     +++++++++++++++++++

这是对的吗?

致以最诚挚的问候。

3 个答案:

答案 0 :(得分:1)

这样更精确:

List example:

     0x1f7d018               0x1f7d038              0x1f7d078
+++++++++++++++++++     +++++++++++++++++++     +++++++++++++++++++
|0x2174010:       |     |0x1f7d070:       |     |0x1f7d090:       |
|key = 10         |     |key = 34         |     |key = 90         |
|&next = 0x1f7d038|++++>|&next = 0x1f7d078|++++>|&next = NULL     |
|                 |     |                 |     |                 |
+++++++++++++++++++     +++++++++++++++++++     +++++++++++++++++++

After deleting the value 34

     0x1f7d018                                      0x1f7d078
+++++++++++++++++++                             +++++++++++++++++++
|0x2174010:       |                             |0x1f7d090:       |
|key = 10         |                             |key = 90         |
|&next = 0x1f7d078|++++++++++++++++++++++++++++>|&next = NULL     |
|                 |                             |                 |
+++++++++++++++++++                             +++++++++++++++++++

答案 1 :(得分:1)

当您从链接列表中删除任何节点时,您实际上正在释放该节点分配的内存。

因此,为了维护您的链表,您需要注意Node2之前的Node1(将被删除)应该直接指向Node2旁边的Node3。

Node1 - >节点2 - >节点3

假设我们正在删除Node2

因此Node1的下一个指针应该指向Node3的地址。并且记得释放Node2分配的内存以避免内存泄漏。

如果是双向链表,则需要注意下一个以及上一个指针。您可以尝试实现双向链表。它一定会帮助您更好地理解。 :)

答案 2 :(得分:0)

更加关注& next

的价值