【问题标题】:Delete in circular doubly linked list connected with head在与头相连的循环双向链表中删除
【发布时间】:2016-06-30 11:41:59
【问题描述】:

我有两个与头和整数元素(无序)连接的循环双向链表。想要在第一个列表中删除包含第二个列表中的值。指针如何工作?如何进行此排除?需要在第一个列表中搜索值以删除第二个列表?我该如何与他们合作?能解释一下算法的操作来解决吗?

示例:

我有两个带头的循环双向链表。

L1:40 100 90 20 10 32 66

L2:60 10 46 30 80 90

我想在第一个列表中删除第二个列表中的值。第一个列表将是:

L1:40 100 20 32 66

我想知道如何使用列表的指针来进行排除。我想要一个伪代码的概念。我已经创建了 C 代码,但我不理解算法。我需要先了解如何做。

【问题讨论】:

  • 不清楚你到底在问什么。你有没有尝试过任何东西?
  • 我有两个带头的循环双向链表。 L1:40 100 90 20 10 32 66 L2:60 10 46 30 80 90 我想在第一个列表中删除第二个列表中的值。然后第一个列表将是:L1:40 100 20 32 66 我想知道如何使用列表来进行排除。我想要一个伪代码的概念。我必须用 C 编写代码,但我不懂算法。我需要先了解该怎么做。
  • 什么是“手”?您指的是“头”吗?
  • 请编辑您的问题并添加该详细信息。尽可能多地向我们提供有关问题的信息。

标签: c data-structures doubly-linked-list circular-list


【解决方案1】:

先写算法的伪代码,然后实现实际功能,可以独立测试。

一般的伪代码类似于:

for each node in list1
{
    if (list2 contains node) 
    {
       remove node from list1
    }
}

假设您的列表和节点定义如下:

struct Node 
{
    struct Node *next;
    struct Node *prev;
    int number;
}

struct List
{
    struct Node *head;
}

// these should be instantiated somewhere
struct List* list1;
struct List* list2;

所以,函数的骨架应该是这样的:

struct Node* node = list1->head;

while (node != null)
{
    // prepare the next node early
    struct Node* next = node->next;

    // check if list2 contains a matching node
    if (match(list2, node->number)) 
    {
        // remove the node properly,
        // updating whatever you need to update
        remove(list1, node);
    }

    // if it's circular, check if this
    // is the last node
    if (next == list1->head)
        break;

    node = next;
}

所以,现在你只剩下实现两个功能了:

// returns true if any node in list contains the specified number
bool match(struct List* list, int number);

// removes the node from the list
void remove(struct List* list, struct Node* node);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    相关资源
    最近更新 更多