LeetCode 147. Insertion Sort List

Posted co0oder

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 };

 

 

24ms

留坑

以上是关于LeetCode 147. Insertion Sort List的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-147-Insertion Sort List

LeetCode 147. Insertion Sort List

Leetcode 147. Insertion Sort List 插入排序 in Java

leetcode 147 Insertion Sort List

Leetcode147. Insertion Sort List

LeetCode 147. Insertion Sort List