Write a Program to Move the last element to Front in a Linked List
Pattern: Traversal and dummy nodes
Walk to the last node, remembering the node before it. Cut the last node off, point it at the old head, and it becomes the new head.
The problem
Given the head of a singly linked list, move its last node to the front and return the new head. For example,
1 → 2 → 3 → 4 → 5 becomes 5 → 1 → 2 → 3 → 4. Lists with zero or one node stay the same.
The link above is a GeeksforGeeks article. The function name moveToFront is this guide's own.
Think first
- Which two pointers must change?
- Why do you need the node before the last one?
- What happens with one node?
Hints
Brute force, and why it fails
Swapping values along the list (moving each value one step right) is O(n) too, but changes values instead of links. Relinking the two ends is cleaner.
The key insight
Moving a node is "delete here, insert there". Deleting the tail needs the node before it, and inserting at the front needs nothing.
Dry run
The list is 1 → 2 → 3 → 4 → 5. Walk with last, keeping prev one step behind.
The plan
if head is null or head.next is null: return head
prev = null, last = head
while last.next is not null: prev = last; last = last.next
prev.next = null
last.next = head
return last
Complexity
- Time
O(n)- Space
O(1)
One walk to the end.
Edge cases
- One node: unchanged.
- Two nodes: they swap.
- Empty list: unchanged.
I've built my logic, show the code
Java
class Solution {
public ListNode moveToFront(ListNode head) {
if (head == null || head.next == null) return head; // zero or one node: nothing to move
ListNode prev = null, last = head;
while (last.next != null) { prev = last; last = last.next; } // last node and the one before it
prev.next = null; // detach the last node
last.next = head; // and put it in front
return last;
}
}C++
class Solution {
public:
ListNode* moveToFront(ListNode* head) {
if (head == NULL || head->next == NULL) return head; // zero or one node: nothing to move
ListNode *prev = NULL, *last = head;
while (last->next != NULL) { prev = last; last = last->next; } // last node and the one before it
prev->next = NULL; // detach the last node
last->next = head; // and put it in front
return last;
}
};Python
from lib import ListNode
class Solution:
def moveToFront(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head # zero or one node: nothing to move
prev, last = None, head
while last.next is not None: # last node and the one before it
prev, last = last, last.next
prev.next = None # detach the last node
last.next = head # and put it in front
return lastCommon mistakes
- Forgetting
prev.next = null, which creates a cycle. - Returning
headinstead of the moved node. - Not handling a single node, where
prevstays null.