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

leetcode Insertion Sort List

时间:2014-09-24 01:57:35      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   for   div   sp   on   

题目:Sort a linked list using insertion sort.

 

代码:

 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     
13         
14     if (head==NULL||head->next==NULL)//only 0,1nodes
15     {
16         return    head;
17     }
18 
19     ListNode    *pNode=head->next,*hNode=head,*tNode=NULL;
20     hNode->next=NULL;
21     while(pNode)
22     {
23         hNode=head;
24 
25     
26 
27       // find where to insert
28       while (hNode)
29       {
30           if (hNode->val>pNode->val)//插入头结点之前
31           {
32               tNode=pNode->next;
33               pNode->next=hNode;
34               head=pNode;
35               hNode=head;
36               pNode=tNode;
37               break;
38           }
39           else if (hNode->next==NULL)//到了最后一个节点
40           {
41               tNode=pNode->next;
42               hNode->next=pNode;
43               pNode->next=NULL;
44               pNode=tNode;
45               break;
46           }
47           else if (hNode->next->val>pNode->val)
48           {
49               tNode=pNode->next;
50               pNode->next=hNode->next;
51               hNode->next=pNode;
52               pNode=tNode;
53               break;
54           }
55           else
56           {
57               hNode=hNode->next;
58           }
59         
60       }
61 
62     }
63     
64     return head;
65     }
66 };

 

 

leetcode Insertion Sort List

标签:des   style   blog   color   io   for   div   sp   on   

原文地址:http://www.cnblogs.com/karcylee/p/3989607.html

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