LeetCode 147. Insertion Sort List
最简单的思路,另开一个list,初始化为仅有head一个节点,head移动到下一个节点。然后开始比较head和tmp的val大小,如果head小,那么插在最前面(注意保持tmp为表头),如果head大,那么tmp一直遍历至表尾或至节点值比head大处。
89ms
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* insertionSortList(ListNode* head) { 12 if(head == NULL) return head; 13 14 ListNode *tmp = head; 15 head = head->next; 16 tmp->next = NULL; 17 18 19 while(head){ 20 if(head->val <= tmp->val){ 21 ListNode* next = head->next; 22 head->next = tmp; 23 tmp = head; 24 head = next; 25 } 26 else{ 27 ListNode* cur = tmp; 28 ListNode* prev = NULL; 29 while(cur && head->val > cur->val){ 30 prev = cur; 31 cur = cur->next; 32 } 33 //prev->head->cur 34 ListNode* next = head->next; 35 prev->next = head; 36 head->next = cur; 37 head = next; 38 39 } 40 } 41 42 return tmp; 43 } 44 };
更快的算法是先比较head和sort链表的开头(resH)的大小,如果head<=resH,那么head插入到表头;否则head和sort链表的表尾(tail)比较大小(而不是从resH开始遍历到比head大的节点),如果head>=tail,head直接插入到表尾,否则tail = resH,再开始遍历到比head大的节点。tail不一定一直为链表的表尾(在 if(tail->next) 情况中)。
24ms
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* insertionSortList(ListNode* head) { 12 if(head == NULL || head->next == NULL) return head; 13 14 ListNode* resH = head, * cur = head->next; 15 ListNode* tail = resH; 16 resH->next = NULL; 17 while(cur){ 18 ListNode* next = cur->next; 19 if(cur->val <= resH->val){ 20 cur->next = resH; 21 resH = cur; 22 } 23 else{ 24 if(cur->val < tail->val){//key: don't compare from the beginning of the list each time, check last end first 25 tail = resH; 26 } 27 while(tail->next && cur->val > tail->next->val){//!!tail->next->val(not tail->val), to ensure tail != NULL 28 tail = tail->next; 29 } 30 if(tail->next){//tail is not the last node in the list 31 cur->next = tail->next; 32 tail->next = cur; 33 } 34 else{//cur->val > tail->val or tail = resH then loop till the last node; in general: temp is the last node 35 tail->next = cur; 36 cur->next = NULL; 37 } 38 } 39 cur = next; 40 } 41 return resH; 42 } 43 };
相同思路,不同写法:
1 class Solution { 2 public: 3 ListNode* insertionSortList(ListNode* head) { 4 ListNode dummy(INT_MIN), *cur=&dummy, *temp; 5 while(head) 6 { 7 if(cur->val>head->val) cur = &dummy; // trick, reset cur only when needed 8 for(; cur->next && cur->next->val<head->val; ) 9 cur = cur->next; 10 temp = head->next; 11 head->next = cur->next; 12 cur->next =head; 13 head = temp; 14 } 15 return dummy.next; 16 } 17 };
创建一个dummy节点,虚节点,充当sort链表的表头,不存值。cur不一定一直保持为表尾。