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

【LeetCode】Insertion Sort List

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

标签:style   blog   class   code   java   ext   

Sort a linked list using insertion sort.

bubuko.com,布布扣
//用到O(N)的额外空间
public class Solution {
    public ListNode insertionSortList(ListNode head) {
        if(head==null||head.next==null)
            return head;
        ListNode root = new ListNode(head.val);
        ListNode cur = head.next;
        while(cur!=null){
            ListNode tempNode = root;
            ListNode pre = root;
            while(tempNode!=null){
                if(cur.val>tempNode.val){
                    pre=tempNode;
                    tempNode=tempNode.next;
                }else{
                    break;
                }
            }           
            if(tempNode==root){
                ListNode newNode = new ListNode(cur.val);
                newNode.next=root;
                root=newNode;
                cur=cur.next;
            }else if(tempNode==null){
                ListNode newNode = new ListNode(cur.val);
                pre.next=newNode;
                cur=cur.next;
            }else{
                ListNode newNode = new ListNode(cur.val);
                pre.next=newNode;
                newNode.next=tempNode;
                cur=cur.next;
            }
            
            
        }
        
        return root;
        
    }
}
bubuko.com,布布扣
bubuko.com,布布扣
public class NSolution {
    public ListNode insertionSortList(ListNode head) {
        if(head==null||head.next==null)
            return head;
        
        ListNode cur = head.next;
        head.next=null;
        while(cur!=null){
            ListNode tempNode = head;
            ListNode pre = head;
            while(tempNode!=null){
                if(cur.val>tempNode.val){
                    pre=tempNode;
                    tempNode=tempNode.next;
                }else{
                    break;
                }
            }           
            if(tempNode==head){
                ListNode newNode = new ListNode(cur.val);
                newNode.next=head;
                head=newNode;
                cur=cur.next;
                
                
                
            }else if(tempNode==null){
                ListNode newNode = new ListNode(cur.val);
                pre.next=newNode;
                cur=cur.next;
            }else{
                ListNode newNode = new ListNode(cur.val);
                pre.next=newNode;
                newNode.next=tempNode;
                cur=cur.next;
            }
            
            
        }
        
        return head;
        
    }
}
bubuko.com,布布扣

 

【LeetCode】Insertion Sort List,布布扣,bubuko.com

【LeetCode】Insertion Sort List

标签:style   blog   class   code   java   ext   

原文地址:http://www.cnblogs.com/yixianyixian/p/3721685.html

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