1

Possible Duplicate:
How to reverse a singly linked list using only two pointers?

This is C code to reverse a linked list. But this isn't producing the desired output.

struct node *temp,*prev;
while(head->next!=NULL)
  {
    temp=prev=head;
    while(temp->next->next!=NULL)
      {
    temp=temp->next;
    prev=prev->next;
      }
    temp=temp->next;
    temp->next=prev;
    prev->next=NULL;
  }

What am I missing?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Srikanth R
  • 410
  • 5
  • 17

2 Answers2

3

You will ask yourself this question often in your career, so it's important that you come up with a solution for this. Here are some pointers:

  1. Write unit tests for your code. Start with an empty list, a list with one element, then two, then three.

  2. Run the code in a debugger.

  3. Add debug printf() statements which show you what the code does as it executes.

Community
  • 1
  • 1
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
1

You don't provide enough informations to have more details, so I guessed it is a singly liked list. If so, you need to run through your list once.

void reverse(struct node **p) {
    struct node *buff = NULL;
    struct node *head = *p;

    while (head != NULL) {
        struct node *temp = head->next;
        head->next = buff;
        buff = head;
        head = temp;
    }   

    *p = buff;
}
md5
  • 23,373
  • 3
  • 44
  • 93