Hi.
I was assigned to reverse a unidirectional linked list in C, where I'm not allowed to make a copy of the given linked list, or to change the actual data.
The only thing I'm allowed to do is to manipulate the list's pointers.
After doing some thinking and scribbling on a piece of paper, I came up with this:


  • Initialize three pointers: p1,p2,p3, for the first, second and third elements, respectively.
  • p1->next=NULL
  • while (p3 != NULL) do
    • p2->next=p1
    • p1=p2
    • p2=p3
    • p3=p3->next

  • p2->next=p1
  • return p2 as the head of the reversed list


This is a pseudo code, of course, as I'm less interested in the actual implementation, and more about the algorithm itself.
I was wondering if there's a more elegant way of doing this, since this gets quite complicated considering the cases where the list has less than three elements in it.