链表排序

链表排序

http://www.nowcoder.com/questionTerminal/d75c232a0405427098a8d1627930bea6

时间复杂度为: nlog(n)
归并排序的时间复杂度是 nlog(n)
解题思路:
1.找到链表的中间节点
2.注意:要保证从headmid之后,就不能继续排序
所以要将mid.next备份为midNext,并将mid.next置为null
3.归并排序链表

import java.util.*;

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

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode sortList (ListNode head){
        // write code here
        if(head == null || head.next == null){
            return head;
        }
        ListNode mid = getMidNode(head);
        // 下面的环节重要
        ListNode midNext = mid.next;
        mid.next = null;
        // 上面的环节重要
        ListNode leftPart = sortList(head);
        ListNode rightPart = sortList(midNext);
        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;
        while(leftPart != null && rightPart != null){
            if(leftPart.val <= rightPart.val){
                cur.next = new ListNode(leftPart.val);
                leftPart = leftPart.next;
            }else{
                cur.next = new ListNode(rightPart.val);
                rightPart = rightPart.next;
            }
            cur = cur.next;
        }
        while(leftPart != null){
            cur.next = new ListNode(leftPart.val);
            cur = cur.next;
            leftPart = leftPart.next;
        }
        while(rightPart != null){
            cur.next = new ListNode(rightPart.val);
            cur = cur.next;
            rightPart = rightPart.next;
        }
        return dummy.next;
    }

    public ListNode getMidNode(ListNode head){
        if(head == null || head.next == null) return head;

        ListNode slow = head;
        ListNode fast = head;
        while(fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
}
全部评论

相关推荐

10-25 00:32
香梨想要offer:感觉考研以后好好学 后面能乱杀,目前这简历有点难
点赞 评论 收藏
分享
joe2333:怀念以前大家拿华为当保底的日子
点赞 评论 收藏
分享
2 收藏 评论
分享
牛客网
牛客企业服务