题解 | #单链表的排序#

单链表的排序

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) {
//         // write code here
//         PriorityQueue<Integer> queue = new PriorityQueue<Integer>(new Comparator<Integer>() {
//             @Override
//             public int compare(Integer o1, Integer o2) {
//                 return o1.compareTo(o2);
//             }
//         });
//         ListNode p = head;
//         while(p != null) {
//             queue.add(p.val);
//             p = p.next;
//         }
//         p = head;
//         while(queue.size() > 0) {
//             p.val = queue.peek();
//             queue.remove();
//             p = p.next;
//         }
//         return head;
//     }
    // 方法2: 归并排序
    public ListNode sortInList (ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while(slow != null && fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        ListNode left = head;
        ListNode right = slow.next;
        slow.next = null;
        left = sortInList(left);
        right = sortInList(right);
        return merge(left, right);
    }

    public ListNode merge(ListNode left, ListNode right) {
        ListNode p = new ListNode(-1);
        ListNode head = p;
        while(left != null && right != null) {
            if (left.val < right.val) {
                p.next = left;
                left = left.next;
            } else {
                p.next = right;
                right = right.next;
            }
            p = p.next;
        }
        if (left != null) {
            p.next = left;
        }
        if (right != null) {
            p.next = right;
        }
        return head.next;
    }

    
}
全部评论

相关推荐

哞客37422655...:github如果提交不是很多 可以不写 可能会是减分项。之前听别人讲过的
点赞 评论 收藏
分享
评论
3
收藏
分享

创作者周榜

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