[LintCode] 链表插入排序

简介: 1 /** 2 * Definition of ListNode 3 * class ListNode { 4 * public: 5 * int val; 6 * ListNode *next; 7 * ListNode(int v...
 1 /**
 2  * Definition of ListNode
 3  * class ListNode {
 4  * public:
 5  *     int val;
 6  *     ListNode *next;
 7  *     ListNode(int val) {
 8  *         this->val = val;
 9  *         this->next = NULL;
10  *     }
11  * }
12  */
13 class Solution {
14 public:
15     /**
16      * @param head: The first node of linked list.
17      * @return: The head of linked list.
18      */
19     ListNode *insertionSortList(ListNode *head) {
20         // write your code here
21         ListNode* new_head = new ListNode(0);
22         new_head -> next = head;
23         ListNode* pre = new_head;
24         ListNode* cur = head;
25         while (cur) {
26             if (cur -> next && cur -> next -> val < cur -> val) {
27                 while (pre -> next && pre -> next -> val < cur -> next -> val)
28                     pre = pre -> next;
29                 /* Insert cur -> next after pre. */
30                 ListNode* temp = pre -> next;
31                 pre -> next = cur -> next;
32                 cur -> next = cur -> next -> next;
33                 pre -> next -> next = temp;
34                 /* Move pre back to the starting node. */
35                 pre = new_head;
36             }
37             else cur = cur -> next;
38         }
39         ListNode* res = new_head -> next;
40         delete new_head;
41         return res;
42     }
43 };

 

目录
相关文章
|
29天前
|
C语言
对链表使用插入排序的C语言实现示例
对链表使用插入排序的C语言实现示例
|
4月前
|
Java Go C++
Golang每日一练(leetDay0116) 路径交叉、回文对
Golang每日一练(leetDay0116) 路径交叉、回文对
31 0
Golang每日一练(leetDay0116) 路径交叉、回文对
|
4月前
|
算法 C++ Go
Golang每日一练(leetDay0050) 对链表进行插入排序、排序链表、直线上最多的点、逆波兰表达式
Golang每日一练(leetDay0050) 对链表进行插入排序、排序链表、直线上最多的点、逆波兰表达式
31 0
Golang每日一练(leetDay0050) 对链表进行插入排序、排序链表、直线上最多的点、逆波兰表达式
|
4月前
|
算法 JavaScript
JS算法-链表插入排序
JS算法-链表插入排序
|
5月前
|
算法 搜索推荐 vr&ar
☆打卡算法☆LeetCode 147. 对链表进行插入排序 算法解析
☆打卡算法☆LeetCode 147. 对链表进行插入排序 算法解析
|
7月前
|
算法
【Leetcode -147.对链表进行插入排序 -237.删除链表中的节点】
【Leetcode -147.对链表进行插入排序 -237.删除链表中的节点】
16 0
|
存储 算法
ARTS-3-算法练习-基于链表的插入排序和链表重排
ARTS-3-算法练习-基于链表的插入排序和链表重排
102 0
|
C++
【LeetCode147】对链表进行插入排序
The number of nodes in the list is in the range [1, 5000]. -5000 <= Node.val <= 5000
73 0
【LeetCode147】对链表进行插入排序
|
存储 Java 算法
[LintCode] Linked List Cycle(带环链表)
描述 给定一个链表,判断它是否有环。 样例 给出 -21->10->4->5, tail connects to node index 1,返回 true。 这里解释下,题目的意思,在英文原题中,tail connects to node index 1 表示的是节点 5 还要链接回索引号 为 1 的节点。
1473 0