码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode – Refresh – Insertion Sort List

时间:2015-03-20 06:56:19      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

Do not forget to break the inner loop, when you find the insert position.

 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 || !head->next) return head;
13         ListNode *result = new ListNode(0);
14         ListNode *old = new ListNode(0);
15         old->next = head;
16         while (old->next) {
17             ListNode *tmp = old->next, *runner = result;
18             old->next = tmp->next;
19             while (runner) {
20                 if (!runner->next || tmp->val < runner->next->val) {
21                     tmp->next = runner->next;
22                     runner->next = tmp;
23                     break;
24                 }
25                 runner = runner->next;
26             }
27         }
28         return result->next;
29     }
30 };

 

LeetCode – Refresh – Insertion Sort List

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4352610.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!