709988. Move Last Element to Front of a Linked List

Easy

Move Last Element to Front of a Linked List

Summary

Given a singly linked list, move the last element to the front of the list. This problem involves working with linked lists and manipulating their structure.

Detailed Explanation

The approach to solve this problem is straightforward: traverse the linked list until you reach the end (i.e., the last node), then reverse the direction of the link for that node to point back to the previous node, effectively moving it to the front. This process can be repeated until the desired result is achieved.

Here's a step-by-step breakdown:

  1. Initialize a pointer prev to NULL, which will keep track of the second-to-last node.
  2. Initialize a pointer curr to the head of the linked list, which will traverse the list.
  3. Traverse the list until you reach the end (i.e., curr->next == NULL). This is done by moving curr one step at a time and updating prev accordingly.
  4. Once you've reached the end, reverse the direction of the link for the last node (curr) to point back to prev. This effectively moves the last element to the front.
  5. Repeat steps 2-4 until the desired result is achieved (i.e., the last element is at the front).

Time complexity: O(n), where n is the number of nodes in the linked list.

Space complexity: O(1), as we only use a constant amount of space to store prev and curr.

Optimized Solutions

Java

View on GeeksforGeeks
public class Solution {
    public void moveLastToFirst(Node head) {
        if (head == null || head.next == null) return;
        
        Node prev = null;
        Node curr = head;
        while (curr.next != null) {
            prev = curr;
            curr = curr.next;
        }
        
        curr.next = head;
        head = curr;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.