Problem:
Sort a linked list using insertion sort.
The node of the linked list is defined as:
1
2
3
4
5
6
7
8 |
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ |
The insertion sorting is one of the simpleset sorting algorithms, which is of O(n^2) time in the worst case.
The key of the insertion sorting is how to keep track of the "sorted" part and "unsorted" part. For sorting an array we just need to keep track the last index of the sorted part; for sorting a linked list, it becomes much complex since you need maintain two pointers, one points to the last sorted element and the other one points to the first unsorted element. Each time, we insert the first unsorted element into the sorted linked list and update the two pointers.
The C++ code is as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36 |
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class
Solution { public : ListNode *insertionSortList(ListNode *head) { if
(head == NULL) return
head; ListNode *sorted_tail = head; ListNode *unsorted_head = sorted_tail->next; ListNode *prev = NULL; ListNode *p = NULL; while
(unsorted_head != NULL) { // Find the position to insert the element after the tail p = head; while
(p->val <= unsorted_head->val && p != unsorted_head) { prev = p; p=p->next; } // Insert if
(p == unsorted_head) sorted_tail = sorted_tail->next; else
{ sorted_tail->next = unsorted_head->next; unsorted_head->next = p; if
(p == head) head = unsorted_head; else
prev->next = unsorted_head; } unsorted_head = sorted_tail->next; } return
head; } }; |
【LeetCode OJ】Insertion Sort List,布布扣,bubuko.com
【LeetCode OJ】Insertion Sort List
原文:http://www.cnblogs.com/zzzdevil/p/3560376.html