Monday, December 30, 2013

Reverse Singly Linked list

//Description:
//out put will be first element if we want to track execution after first execution of while loop
// out put will be reverse of first two element if we are doing it for 2nd time
//ex: Original list: 10, 15, 20,5
// after first while execution : list will give out put as 10
//second exeecutin 15 , 10 , same execution will follow for rest
// third execution: 20 , 15, 10 etc



void single_link_list::reverse_linked_list()
{
node* current_node = first_node;
node* next_node;
node* prev_node = NULL ;
int count = 0;
if(first_node->link == NULL)
{
printf("there is only one element in the list Hence can not reverse");
}
else
{
      while(current_node != NULL)
              {
next_node = current_node->link; // this is to store the address of broken node link
current_node->link = prev_node; // this is to revese the link
prev_node = current_node; // prev node to current to make sure link is established after reversing
current_node = next_node; // iterating to all nodes
}
         first_node = prev_node; // just changing the head of the list
}
}

No comments: