2

Possible Duplicate:
Reverse a singly linked list

How to reverse a singly linked list in single for loop ? This was the question which was asked in an interview .

Community
  • 1
  • 1
  • http://en.cppreference.com/w/cpp/container/list/reverse - you don't even need a loop – Mat Sep 16 '12 at 10:55
  • thanx Mat. . . but reversing should be done without using any function like sort or reverse. –  Sep 16 '12 at 11:02
  • Well that's been asked & answered a lot here and elsewhere. See the second link. – Mat Sep 16 '12 at 11:03

1 Answers1

1

In pseudo code this would look like:

// Cache the start element
current = first;
next = current->next;
while (next != null) {
   // Cache the next pointer to not lose the reference
   temp = next->next;
   next->next = current;
   // Increment
   current = next;
   next = temp;
}
first = current;

I know it's not in a for loop but it can easily be rewritten to be. With the while it makes it a bit more readable.

Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100