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}.

Practice this problem

The idea is to make the linked list circular and then break the chain before the last node after making its head to point to the last node. Following is the C, Java, and Python program that demonstrates it:

C


Download  Run Code

Output:

4 —> 1 —> 2 —> 3 —> NULL

Java


Download  Run Code

Output:

4 —> 1 —> 2 —> 3 —> null

Python


Download  Run Code

Output:

4 —> 1 —> 2 —> 3 —> None

We can solve this problem recursively as well. Following is its simple recursive implementation in C, Java, and Python:

C


Download  Run Code

Output:

4 —> 1 —> 2 —> 3 —> NULL

Java


Download  Run Code

Output:

4 —> 1 —> 2 —> 3 —> null

Python


Download  Run Code

Output:

4 —> 1 —> 2 —> 3 —> None

The time complexity of both above-discussed methods is O(n), where n is the length of the linked list. The iterative version doesn’t require any extra space, whereas the recursive version use stack space proportional to the lists’ length.