VOOZH about

URL: https://www.geeksforgeeks.org/dsa/exchange-first-last-node-circular-linked-list/

⇱ Exchange first and last nodes in Circular Linked List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Exchange first and last nodes in Circular Linked List

Last Updated : 22 Feb, 2023

Given Circular linked list exchange the first and the last node. The task should be done with only one extra node, you can not declare more than one extra node, and also you are not allowed to declare any other temporary variable. 

Note: Extra node means the need of a node to traverse a list.  

👁 https://media.geeksforgeeks.org/wp-content/uploads/Capturehgh.png


Examples: 

Input : 5 4 3 2 1
Output : 1 4 3 2 5

Input  : 6 1 2 3 4 5 6 7 8 9
Output : 9 1 2 3 4 5 6 7 8 6

Method 1: (By Changing Links of First and Last Nodes)

We first find a pointer to the previous to the last node. Let this node be p. Now we change the next links so that the last and first nodes are swapped.  


Output
List Before: 6 1 2 3 4 5 
List After: 5 1 2 3 4 6 

Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of nodes in the linked list.
Auxiliary Space: O(1), as we are not using any extra space.

Method 2: (By Swapping Values of First and Last nodes)

Algorithm: 

  1. Traverse the list and find the last node(tail).
  2. Swap data of head and tail.

Below is the implementation of the algorithm:


Output
List Before: 6 1 2 3 4 5 
List After: 5 1 2 3 4 6 

Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of nodes in the linked list.
Auxiliary Space: O(1), as we are not using any extra space.

Comment
Article Tags: