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

[Leetcode] Insertion Sort List

时间:2014-11-17 09:11:05      阅读:218      评论:0      收藏:0      [点我收藏+]

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

Sort a linked list using insertion sort.

 

Solution:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode insertionSortList(ListNode head) {
14         if(head==null||head.next==null)
15             return head;
16         ListNode dummy=new ListNode(-1);
17         ListNode pre,next;
18         while(head!=null){
19             pre=findPosition(dummy,head.val);
20             next=pre.next;
21             pre.next=new ListNode(head.val);
22             pre.next.next=next;
23             head=head.next;
24         }
25         return dummy.next;
26     }
27 
28     private ListNode findPosition(ListNode dummy, int val) {
29         // TODO Auto-generated method stub
30         ListNode pre=dummy, next=pre.next;
31         while(next!=null&&next.val<=val){
32             next=next.next;
33             pre=pre.next;
34         }
35         return pre;
36     }
37 }

 

[Leetcode] Insertion Sort List

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

原文地址:http://www.cnblogs.com/Phoebe815/p/4102823.html

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