Search code examples
cdata-structuresdequecircular-list

Reversing a circular deque without a sentinel


Hey Stackoverflow I'm working on my homework and I'm trying to reverse a circular-linked deque without a sentinel. Here are my data structures:

struct DLink {

 TYPE value;

 struct DLink * next;

 struct DLink * prev;
};

struct cirListDeque {

 int size;
 struct DLink *back;
};

Here's my approach to reversing the deque:

void reverseCirListDeque(struct cirListDeque* q) {

struct DLink* current;

struct DLink* temp;



temp = q->back->next;

q->back->next = q->back->prev;

q->back->prev = temp;



current = q->back->next;

while(current != q->back) {

    temp = current->next;

    current->next = current->prev;

    current->prev = temp;



    current = current->next;

}

}

However when I run it and put values 1, 2 and 3 on it (TYPE is just a alias for int in this case) and reverse it I get 2, 1, 3. Does anyone have any ideas as to what I may be doing wrong?

Thanks in advance.


Solution

  • current = q->back->next;
    
    while(current != q->back->next)
    {
        /* This code will never run, cause you guaranteed right before the while
         * that current == q->back->next .
         */
    }
    

    Update: What you need to do now, once you've reversed all the pointers (which seems to work now, judging by your results), is set your "back" pointer to back->prev.