LeetCode 147. Insertion Sort List
Given the head
of a singly linked list, sort
the list using insertion sort
, and return the sorted list’s head.
Input: head = [4,2,1,3]
Output: [1,2,3,4]
method:
head
指向要插入的元素,pre
遍历已排序的链表,找到小于head->val
的最大值或者最末尾的元素,插入head
插入分两步:
head
的next
指向pre
的next
pre
的next
指向head
ListNode* insertionSortList(ListNode* head) {
ListNode *dummy = new ListNode(0);
ListNode *pre = dummy;
while (head) {
ListNode *tmp = head->next;
while (pre->next && pre->next->val < head->val)
pre = pre->next;
head->next = pre->next; // 1
pre->next = head; // 2
head = tmp; // head回到原来的链表
pre = dummy; // pre回到开头
}
return dummy->next;
}