题解 | #单链表的排序#
单链表的排序
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;
}
}
查看10道真题和解析