147. [M] Insertion Sort List
https://leetcode.com/problems/insertion-sort-list/
class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
// (dummy) -> (4/head) -> (2) -> (1) -> (3)
while (head != null && head.next != null) {
if (head.val < head.next.val) {
head = head.next;
continue;
}
ListNode p = dummy;
// (dummy/p) -> (4/head) -> (2) -> (1) -> (3)
while (p.next.val < head.next.val) {
p = p.next;
}
// (dummy/p) -> (4/head) -> (2) -> (1) -> (3)
ListNode t = head.next;
// (dummy/p) -> (4/head) -> (2/t) -> (1) -> (3)
head.next = head.next.next;
// (dummy/p) -> (4/head) -> (1) -> (3)
// (2/t) -> (1) -> (3)
t.next = p.next;
// (dummy/p) -> (4/head) -> (1) -> (3)
// (2/t) -> (4/head) -> (1) -> (3)
p.next = t;
// (dummy/p) -> (2/t) -> (4/head) -> (1) -> (3)
}
return dummy.next;
}
}理解
最后更新于