VOOZH about

URL: https://www.geeksforgeeks.org/dsa/move-last-element-to-front-of-a-given-linked-list/

⇱ Move last element to front of a given Linked List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Move last element to front of a given Linked List

Last Updated : 26 Aug, 2024

Given a singly linked list. The task is to move the last node to the front in a given List.

Examples:


Input: 2->5->6->2->1
Output: 1->2->5->6->2
Explanation : Node 1 moved to front.

👁 Image

Input: 1->2->3->4->5
Output: 5->1->2->3->4
Explanation : Node 5 moved to front.

[Expected Approach] Traverse Till Last Node - O(n) Time and O(1) space:

Traverse the list till the last node. Use two pointers to store the reference of the last node and second last node. After the end of loop, make the second last node as the last node and the last node as the head node.

Below is the implementation of the above approach:


Output
Linked list before: 
1 2 3 4 5 
Linked list after: 
5 1 2 3 4 

Time Complexity: O(n), As we need to traverse the list once.
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: