标签:
最简单的思路,另开一个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 };
24ms
留坑
LeetCode 147. Insertion Sort List
标签:
原文地址:http://www.cnblogs.com/co0oder/p/5350912.html