题解 | #单链表的排序#

单链表的排序

http://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08

选择排序 从无序里面选最小的 放入有序

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
        public ListNode sortInList (ListNode head) {
          //边界条件
        if (head == null || head.next == null) {
            return head;
        }
		//哑节点
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode sorted = dummy;
		//遍历
        while (sorted.next != null) {
            ListNode pre = sorted;
            ListNode cur = sorted.next;
            ListNode preMin = null;
            ListNode min = null;
            while (cur != null) {
                if (min == null || cur.val < min.val) {
                    preMin = pre;
                    min = cur;
                }
                pre = pre.next;
                cur = cur.next;
            }

            preMin.next = min.next;
            min.next = sorted.next;
            sorted.next = min;
            sorted = min;
        }
        return dummy.next;
    }
}
全部评论

相关推荐

把球:这个听过,你加了就会发现是字节的hr
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务