Simple Java Solution based on heap sort utilizing PriorityQueue


  • 1
    J
    public class Solution {
        
        private class myComparator implements Comparator<ListNode>{
            @Override
            public int compare(ListNode l1,ListNode l2){
                return Integer.compare(l1.val,l2.val);
            }
        }
        public ListNode sortList(ListNode head) {
            if(head==null||head.next==null)return head;
            PriorityQueue<ListNode> que=new PriorityQueue<ListNode>(10,new myComparator());
            ListNode cur=head;
            while(cur!=null){
                que.add(cur);
                cur=cur.next;
            }
            ListNode helper=new ListNode(0);
            ListNode ptr=helper;
            while(!que.isEmpty()){
                ptr.next=que.poll();
                ptr=ptr.next;
            }
            ptr.next=null;
            return helper.next;
        }
    }

  • 0
    D

    not constant space


Log in to reply
 

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