Saturday, January 23, 2010

link list reversal

here i am providing a very simple algorithm (a program indeed) for reversing a given linked list....

Assumption:- head pointer is provided, the structure of node is as follows

typedef struct node
{
int val;
node *next;
}item;

item* revlist(item *head)
{

/*for reversing , we have to just reverse the next pointer in each node..means if the node A was
pointing to node B and node B was pointing to node C then for reversing we have to,first make A pointed by B's next and B pointed by C's next..means..a parent will become child now and grandchild will become child for the next operation*/


item *parent;
item *child;
item *grandchild;
parent = head;
child = parent->next;
grandchild = child->next;
parent->next = NULL;

while(child!=NULL)
{
child->next = parent;
parent = child;
child = grandchild;
if(child!=NULL)
grandchild = child->next;
}
head = parent;
return head;
}