LeetCode | Insertion Sort List

题目:Sort a linked list using insertion sort.

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

//插入排序,每次把A[p]插入到正确的位置
public class Solution {
    public ListNode insertionSortList(ListNode head) {
        if ( head==null || head.next==null ) return head; 
        ListNode newHead = new ListNode(0);
        newHead.next = head;
        
        ListNode pre = head;          //取例: 4 8 3 1 5
        ListNode post = head.next;   //pre和post用来向后遍历list,查找是否有逆序的存在
        
        while( post != null){
            if( post.val >= pre.val )  //正常情况(4<8),继续向后前进查找逆序
            {
                pre = pre.next;
                post = post.next;
            }
            else{                     //说明查找到了逆序的存在(8>3),要利用插入排序,把post<插入>到正确的位置
                ListNode insertPre = newHead;
                ListNode insertPost = newHead.next;  //这两个变量用来查找插入的位置,插入到insertPre与insertPost之间
                
                while( insertPost.val < post.val ){     //查找插入位置,插入位置应该在List中第一个大于A[p]之前,例如3要插入到4之前
                                                        //第一个大于A[p]的位置即insertPost
                                                        //注:插入A[p]时,其左边已处于排序好的状态
                     insertPre = insertPost;
                     insertPost = insertPost.next;
                }
                pre.next = post.next;  //在把post插入到正确位置之前,要记得把pre和后边的list接上,把8和1连上
                
                insertPre.next = post;
                post.next = insertPost;  //此两行即把post插入到正确的位置
                
                post = pre.next;    //在进行下一次循环前,重新把post置为pre的下一个
            }
        }
       return newHead.next;
    }
}

 

posted @ 2014-10-26 09:50  Mr.do  阅读(122)  评论(0编辑  收藏  举报