In our C-programming classes we had been doing lots of programs using linked list. In the initial classes of linked lists the programs we were made to do were things like insertion, deletion, searching of nodes of a linked list. Later we get on to reversal of a given linked list and most of us do it comfortably when given without any constrains.
This program can be made a bit interesting and may even be a brainteaser for beginners if we add a condition that only one extra variable can be used within the function reverse (head). I wrote one program for the same and is given below.
node * reverse(node * head)
{
node * t = head;
if(t == null)
return null;
if(t->link == null)
return head;
while(t->link->link != null)
t = t->link;
t->link->link = t;
t = t->link;
t->link->link = null;
rev(head);
return t;
}
typedef struct node {
int data;
struct node * link;
}node;
A much more cool one is to do without any extra variable. I tried but couldn’t come up with an answer.. and think that reversal cant be done without the help of at least one extra variable. Let me know if u had an answer for this too…