class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null) {
return head;
}
ListNode dummy = new ListNode(0, head);
ListNode lastSorted = head, current = head.next;
while (current != null) {
if (lastSorted.val < current.val) {
lastSorted = lastSorted.next;
} else {
ListNode prev = dummy;
while (current.val > prev.next.val) {
prev = prev.next;
}
lastSorted.next = current.next;
current.next = prev.next;
prev.next = current;
}
current = lastSorted.next;
}
return dummy.next;
}
}
来源:LeetCode官方
|