在 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;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM