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;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值