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

[leetcode]Insertion Sort List

时间:2014-07-22 00:23:34      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   re   

Insertion Sort List

Sort a linked list using insertion sort.

 

算法思路:

最基本的插入排序,时间复杂度O(n*n),空间复杂度O(1)

代码:

 1 public class Solution {
 2     public ListNode insertionSortList(ListNode head) {
 3         if(head == null || head.next == null) return head;
 4         ListNode list = new ListNode(0);
 5         list.next = head;
 6         head = head.next;
 7         list.next.next = null;
 8         while(head != null){
 9             ListNode tail = list;
10             ListNode node = head;
11             head = head.next;
12             node.next = null;
13             while(tail != null){
14                 if(tail.next == null){
15                     tail.next = node;
16                     break;
17                 }
18                 if(tail.next.val > node.val){
19                     node.next = tail.next;
20                     tail.next = node;
21                     break;
22                 }else{
23                     tail = tail.next;
24                 }
25             }
26         }
27         return list.next;
28     }
29 }

[leetcode]Insertion Sort List,布布扣,bubuko.com

[leetcode]Insertion Sort List

标签:style   blog   http   color   io   re   

原文地址:http://www.cnblogs.com/huntfor/p/3858417.html

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