Leetcode 147. Insertion Sort List 插入排序 in Java

147. Insertion Sort List

  • Total Accepted: 80869
  • Total Submissions: 263074
  • Difficulty: Medium

 

Sort a linked list using insertion sort.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode insertionSortList(ListNode head) {
        
        if(head==null || head.next==null) return head;
    
        ListNode newHead=new ListNode(0);//后面使用tmp.next与pre比较,所以增加一个新的newHead
        
        ListNode cur=head;
        
        while(cur!=null){
            ListNode next=cur.next;//放这里而不放在循环末尾,防止out of index
            ListNode tmp=newHead;
            while(tmp.next!=null && tmp.next.val<cur.val){
                tmp=tmp.next;
            }
            cur.next=tmp.next;
            tmp.next=cur;
            cur=next;
  
        }
       return newHead.next;
    }
}

 

  

posted on 2016-09-07 20:56  颜YQ  阅读(177)  评论(0编辑  收藏  举报

导航