Leetcode 147. Insertion Sort List
You are given the head of a singly linked list. You need to sort the list using insertion sort and return the sorted list’s head.
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
Insertion Sort works similarly to the way you sort playing cards in your hands. We take one element at a time and place it in the correct position relative to the already sorted elements.
We’ll use a dummy node at the start of our sorted list to simplify insertion logic by avoiding special cases for head insertions.
Here is the Java implementation of the problem:
public class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null) {
return null;
}
ListNode dummy = new ListNode(0); // dummy node
ListNode curr = head; // pointer to iterate through the original list
while (curr != null) {
ListNode prev = dummy; // always point to the dummy node initially
ListNode next = curr.next; // store next node to move forward later
// Find the correct position to insert the current node
while (prev.next != null && prev.next.val < curr.val) {
prev = prev.next;
}
// Insert the current node in the sorted list
curr.next = prev.next;
prev.next = curr;
// Move to the next node in the original list
curr = next;
}
return dummy.next; // the sorted list starts from dummy.next
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?