Search code examples
linked-listtraversaldoubly-linked-list

mirror point in circular doubly linked list


I am supposed to count and list the mirror points in the circular doubly linked list. A particular element in the list is a mirror point if traversing the list in the clockwise direction from that element results in the same sequence of values as traversing the list from that element in the anticlockwise direction. All I can do is traverse in forward and backward direction.

void traversal(struct Node* start)
{
    struct Node *temp = start;
 
    printf("\nTraversal in forward direction \n");
    while (temp->next != start)
    {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("%d ", temp->data);
 
    printf("\nTraversal in reverse direction \n");
    Node *last = start->prev;
    temp = last;
    while (temp->prev != last)
    {
        printf("%d ", temp->data);
        temp = temp->prev;
    }
    printf("%d ", temp->data);
}

any idea of how to solve the problem will be appreciated...


Solution

  • You have the ingredients. You should perform both traversals in tandem: use distinct pointers for these traversals, and move them at the same time:

    bool traversal(struct Node* start)
    {
        struct Node *forward = start->next;
        struct Node *backward = start->prev;
     
        while (forward != start)
        {
            if (forward->data != backward->data) {
                return false;
            }
            forward = forward->next;
            backward = backward->prev;
        }
        return true;
    }
    

    This will return true when the given node is a mirror point. Remains for you to call this function for each node and count the number of times you get true as a return value...