Losing head/tail while rewiring
Wrong move: Pointer updates overwrite references before they are saved.
Usually fails on: List becomes disconnected mid-operation.
Fix: Store next pointers first and use a dummy head for safer joins.
Move from brute-force thinking to an efficient approach using linked list strategy.
Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.
The steps of the insertion sort algorithm:
The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.
Example 1:
Input: head = [4,2,1,3] Output: [1,2,3,4]
Example 2:
Input: head = [-1,5,3,4,0] Output: [-1,0,3,4,5]
Constraints:
[1, 5000].-5000 <= Node.val <= 5000Problem summary: Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head. The steps of the insertion sort algorithm: Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there. It repeats until no input elements remain. The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Linked List
[4,2,1,3]
[-1,5,3,4,0]
sort-list)insert-into-a-sorted-circular-linked-list)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #147: Insertion Sort List
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(head.val, head);
ListNode pre = dummy, cur = head;
while (cur != null) {
if (pre.val <= cur.val) {
pre = cur;
cur = cur.next;
continue;
}
ListNode p = dummy;
while (p.next.val <= cur.val) {
p = p.next;
}
ListNode t = cur.next;
cur.next = p.next;
p.next = cur;
pre.next = t;
cur = t;
}
return dummy.next;
}
}
// Accepted solution for LeetCode #147: Insertion Sort List
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func insertionSortList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
dummy := &ListNode{head.Val, head}
pre, cur := dummy, head
for cur != nil {
if pre.Val <= cur.Val {
pre = cur
cur = cur.Next
continue
}
p := dummy
for p.Next.Val <= cur.Val {
p = p.Next
}
t := cur.Next
cur.Next = p.Next
p.Next = cur
pre.Next = t
cur = t
}
return dummy.Next
}
# Accepted solution for LeetCode #147: Insertion Sort List
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
dummy = ListNode(head.val, head)
pre, cur = dummy, head
while cur:
if pre.val <= cur.val:
pre, cur = cur, cur.next
continue
p = dummy
while p.next.val <= cur.val:
p = p.next
t = cur.next
cur.next = p.next
p.next = cur
pre.next = t
cur = t
return dummy.next
// Accepted solution for LeetCode #147: Insertion Sort List
struct Solution;
use rustgym_util::*;
trait Insertion {
fn insert(self, link: ListLink) -> ListLink;
}
impl Insertion for ListLink {
fn insert(self, mut link: ListLink) -> ListLink {
let val = link.as_ref().unwrap().val;
if let Some(mut node) = self {
if node.val > val {
link.as_mut().unwrap().next = Some(node);
link
} else {
node.next = node.next.take().insert(link);
Some(node)
}
} else {
link
}
}
}
impl Solution {
fn insertion_sort_list(mut head: ListLink) -> ListLink {
let mut prev = None;
while let Some(mut node) = head {
head = node.next.take();
prev = prev.insert(Some(node));
}
prev
}
}
#[test]
fn test() {
let head = list!(4, 2, 1, 3);
let res = list!(1, 2, 3, 4);
assert_eq!(Solution::insertion_sort_list(head), res);
let head = list!(-1, 5, 3, 4, 0);
let res = list!(-1, 0, 3, 4, 5);
assert_eq!(Solution::insertion_sort_list(head), res);
}
// Accepted solution for LeetCode #147: Insertion Sort List
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #147: Insertion Sort List
// /**
// * Definition for singly-linked list.
// * public class ListNode {
// * int val;
// * ListNode next;
// * ListNode() {}
// * ListNode(int val) { this.val = val; }
// * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
// * }
// */
// class Solution {
// public ListNode insertionSortList(ListNode head) {
// if (head == null || head.next == null) {
// return head;
// }
// ListNode dummy = new ListNode(head.val, head);
// ListNode pre = dummy, cur = head;
// while (cur != null) {
// if (pre.val <= cur.val) {
// pre = cur;
// cur = cur.next;
// continue;
// }
// ListNode p = dummy;
// while (p.next.val <= cur.val) {
// p = p.next;
// }
// ListNode t = cur.next;
// cur.next = p.next;
// p.next = cur;
// pre.next = t;
// cur = t;
// }
// return dummy.next;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Copy all n nodes into an array (O(n) time and space), then use array indexing for random access. Operations like reversal or middle-finding become trivial with indices, but the O(n) extra space defeats the purpose of using a linked list.
Most linked list operations traverse the list once (O(n)) and re-wire pointers in-place (O(1) extra space). The brute force often copies nodes to an array to enable random access, costing O(n) space. In-place pointer manipulation eliminates that.
Review these before coding to avoid predictable interview regressions.
Wrong move: Pointer updates overwrite references before they are saved.
Usually fails on: List becomes disconnected mid-operation.
Fix: Store next pointers first and use a dummy head for safer joins.