a-chris
a-chris

Reputation: 129

Reverse double linked list

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

Upvotes: 0

Views: 185

Answers (3)

kmkaplan
kmkaplan

Reputation: 18960

You have to set *s to the new head of the list. That is the old tail of the list, the last element you process.

void snake_reverse(struct snake **s) {
    struct snake *last, *tmp = NULL;
    last = *s;
    while (last !=  NULL) {
        *s = last
        tmp = last->prev;
        last->prev = last->next;
        last->next = tmp;
        last = last->prev;
    }
}

Upvotes: 1

cleblanc
cleblanc

Reputation: 3688

You're never setting the new head of the list since tmp is always NULL after the while loop. Try this;

void snake_reverse(struct snake **s) {
  struct snake *last, *newHead, *tmp = NULL;

  last = *s;

  while (last !=  NULL)
  {
     tmp = last->prev;
     if (tmp!=NULL)
       newHead = tmp;
     last->prev = last->next;
     last->next = tmp;
     last = last->prev;
  }

  *s = newHead;
}

Upvotes: 0

Rick de Gier
Rick de Gier

Reputation: 62

I am not sure but I think that the last line of code in your while loop is wrong. As I understand the last variable is the tail of the snake. That means that last->next = null. In the second line of code in your while you make the previous of last null and in the last line of code in the while the last becomes 0. I think that changing your last line of code in the while loop will change this.

last = last->next

Upvotes: 0

Related Questions