题解 | #单链表的排序#

单链表的排序

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


/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */
//归并排序
public class Solution {
    /**
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    public ListNode sortInList (ListNode head) {
        // write code here、
        if(head == null || head.next == null){
              return head;
        }
        ListNode fast = head.next;
        ListNode slow = head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode flu = slow.next;
        slow.next = null;
        ListNode left = sortInList(head);
        ListNode right = sortInList(flu);
        ListNode node = new ListNode(-1);
        ListNode pre = node;
        while(left != null && right != null){
            if(left.val < right.val){
                pre.next = left;
                left  = left.next;
            }else{
                pre.next = right;
                right  = right.next;
            }
            pre =  pre.next;
        }
        if(left != null){
             pre.next = left;
        }else{
             pre.next = right;
        }
        return node.next;
    }
}
全部评论

相关推荐

12-22 16:31
已编辑
桂林电子科技大学 Python
很奥的前端仔:如果你接了offer 临时又说不去 hr确实要多做一些工作。 当然如果是接offer之前当我没说
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务