I have to write a function to reverse a double linked list, so that the tail becomes the head.
For example, the elements before: {(1,1), (1,2), (2,2), (2,3)}
after: {(2,3), (2,2), (1,2), (1,1)}
Here's the structure:
struct snake {
unsigned int i;
unsigned int j;
struct snake *next;
struct snake *prev;
};
This is the function prototipe I must use:
void snake_reverse(struct snake **s);
I tried something like this and several other attempts
void snake_reverse(struct snake **s) {
struct snake *last, *tmp = NULL;
last = *s;
while (last != NULL)
{
tmp = last->prev;
last->prev = last->next;
last->next = tmp;
last = last->prev;
}
if(tmp != NULL )
*s = tmp->prev;
}
Also tried this:
while (last != NULL)
{
tmp = last->next;
last->next = last->prev;
last->prev = tmp;
last = tmp;
}
if(tmp != NULL )
*s = tmp;
but he doesn't work. I'm almost sure I'm not wrong. The first ->prev of the list is NULL, the last ->next of the list is NULL.
I get no errors or crash, but the task of the function is to invert the direction of the snake by reversing all elements and changing the head of the list. Can you say what's wrong here?
EDIT: The problem was in another module of the program not made by me.
Anyway the best solution is that of kmkaplan. Thanks everybody
last = last->prev: would it make sense to havelast = tmpinstead?nextorprevare the end markers, and setheadandtail. But can you side-step the problem by setting a flag to tell you in which direction the list is to be parsed? Head to tail, or tail to head. To reverse direction, you would invert the flag. Job done.