Exchange First and Last nodes in Circular Linked List


Today we will be discussing the algorithm to Exchange First and Last nodes in Circular Linked List . But, if you are unfamiliar with the concepts of circular linked list then refer to this link. Suppose we have circular linked list 1->2->3->4 and 4 points to 1. Then after swapping the first and last node the circular linked list will look like 4->2->3->1 and 1 points to 4. Now, let's discuss the procedure:

Procedure


1. First we will make a circular linked list. 
2. Now we will make a variable which will point to the first node. 
3. Then we will make another variable which will point to the last node.
4. At last, we will swap the data of these 2 variables.

Exchange First and Last nodes in Circular Linked List


Code




Explanation of code


1. First we will write a simple code of circular linked list which will have 3 functions:
     - insert() - which will insert elements in the circular linked list.
     - assignhead() - to make a link between last and first node.
     - disp() - which will display the circular linked list.
2. Insert some values in the circular linked list.
3. Now we have created a function named Swap() to Exchange First and Last nodes in Circular Linked List.
4. First we have created a pointer to node variable temp which is initialized to head. So, temp is pointing to the first node.
    struct node* temp=head;
5. Next, we have created another pointer to node variable temp1 which is also initialized to head. But, later on we will use temp1 to point to the last node of list.
   struct node* temp1=head; 
6. Now we are using a while loop to traverse the list till end. Focus on the test condition of while loop. We have written that we will traverse the list until the next of the temp1 points to head OR in other words we are traversing the list till the last node only. So, this condition will make temp1 point to the last node. Inside the while loop we are just moving to the next node.
   while(temp1->next!=head)
   {
         temp1=temp1->next;
   }
7. At last we have used the in-built swap() to swap the data of temp and temp1.


Post a Comment (0)
Previous Post Next Post