Move last node to front in a given Linked List

Given a linked list, move its last node to the front.

 

For example, list {1, 2, 3, 4} should be changed to {4, 1, 2, 3}.

 


 

The idea is to make the linked list circular and then break the chain before the last node after making it’s head to point to last node.

 
C++ implementation –
 

Download   Run Code

Output:

4 -> 1 -> 2 -> 3 -> null

 


 

We can solve this problem recursively as well. Below is its simple recursive implementation –

 
C++ implementation –
 

Download   Run Code

Output:

4 -> 1 -> 2 -> 3 -> null

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂