Move last node to front in a given Linked List

Given a linked list, move its last node to 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

Download   Run Code

Output:

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

Java

Download   Run Code

Output:

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

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

C

Download   Run Code

Output:

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

Java

Download   Run Code

Output:

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

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂


Leave a Reply

avatar
  Subscribe  
newest oldest most voted
Notify of
Ajay singh
Guest

Nice post and nice explanation.