Move the last element to the front

Easy

Problem

Move the last node of the linked list to the front and return the new head.

Example 1

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

Also asked as: Write a Program to Move the last element to Front in a Linked List

Test cases

Case 1

Input:    [1,2,3,4,5]
Expected: [5,1,2,3,4]

Case 2

Input:    [1,2]
Expected: [2,1]

Case 3

Input:    [7]
Expected: [7]

Case 4

Input:    []
Expected: []

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution1 approach

1. Walk to the second-last node

Time O(n)Space O(1)

Detach the last node, point it at the old head, make it the new head.

function moveLastToFront(head) {
if (!head || !head.next) return head;
let secondLast = head;
while (secondLast.next.next) secondLast = secondLast.next;
const last = secondLast.next;
secondLast.next = null;
last.next = head;
return last;
}