题解 | #链表排序#
链表排序
http://www.nowcoder.com/practice/d75c232a0405427098a8d1627930bea6
public ListNode sortList(ListNode head) {
if( head == null ){
return head;
}
List<ListNode> list = new LinkedList<ListNode>(); ListNode node = head; while( node!=null ){ list.add(node); node = node.next; } list.sort(new Comparator<ListNode>() { @Override public int compare(ListNode o1, ListNode o2) { return o1.val > o2.val ? 1 : (o1.val == o2.val ? 0 : -1); } }); head = new ListNode(0); ListNode r = head; for (ListNode n : list) { System.out.print(n.val + " "); r.next = n; r = n; } r.next = null; return head.next; }