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

Problem Insertion Sort List

时间:2014-07-07 16:57:55      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   strong   for   

Problem Description:

Sort a linked list using insertion sort.

Solution:

 1 public class Solution {
 2     public ListNode insertionSortList(ListNode head) {
 3         int length = 0;
 4         ListNode p = head;
 5         while (p != null) {
 6             length++;
 7             p = p.next;
 8         }
 9 
10         if (length <= 1) return head;
11 
12         ListNode[] list = new ListNode[length];
13         p = head;
14         for (int i = 0; i < list.length; i++) {
15             list[i] = p;
16             p  =p.next;
17         }
18 
19         for (int i = 1; i < list.length; i++) {
20             int j = i;
21             while (j > 0 && list[j-1].val > list[j].val) {
22                 ListNode temp = list[j-1];
23                 list[j-1] = list[j];
24                 list[j] = temp;
25                 j--;
26             }
27         }
28 
29         for (int i = 0; i < list.length - 1; i++) {
30             list[i].next = list[i+1];
31             if (i == list.length - 2 ) {
32                 list[i + 1].next = null;
33             }
34         }
35 
36         return list[0];
37     
38     }

 

Problem Insertion Sort List,布布扣,bubuko.com

Problem Insertion Sort List

标签:des   style   blog   color   strong   for   

原文地址:http://www.cnblogs.com/liew/p/3815011.html

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