在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
import java.util.LinkedList;
import java.util.List;
class Solution {
    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;
    }
}

 

posted @ 2019-07-09 11:06  紫色的雪  阅读(1508)  评论(0编辑  收藏  举报