11-lines concise JAVA (PriorityQueue)


  • 0
        public ListNode sortList(ListNode head) {
            if(head == null || head.next == null)
                return head;
            PriorityQueue<ListNode> qu = new PriorityQueue<>((a,b) -> (a.val - b.val));
            ListNode res, cur;
            
            for(cur = head; cur != null; cur = cur.next)
                qu.offer(cur);
            
            res = qu.poll();
            for(cur = res; !qu.isEmpty(); cur = cur.next) 
                cur.next = qu.poll();
            
            cur.next = null;
            return res;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.