简体   繁体   中英

Delete in circular doubly linked list connected with head

I have two circular doubly linked list connected with head and integer elements (unordered). wanted to delete in first list contains the values in the second list. How work pointer ? how to make this exclusion? Need to search values in the first list to delete the second list? how can I work with them? Could explain the operation of the algorithm to solve it?

Exemple:

I have two circular doubly linked lists with head.

L1: 40 100 90 20 10 32 66

L2: 60 10 46 30 80 90

I want to delete in the first list the values that are in the second. The first list will then be:

L1: 40 100 20 32 66

I would like to know how to work with the pointer of the lists in order to make this exclusion. I wanted a notion in pseudocode. I have create to code in C but I do not understand the algorithm. I need to understand how to do before.

Start by writing the pseudocode of the algorithm, then implement actual functions, which can be tested independently.

General pseudocode would be something like:

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

Presuming your lists and nodes are defined something like:

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;

So, the skeleton of the function would be something like:

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;
}

So, now you are only left with implementing two functions:

// 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM