Java code accepted


  • 0
    L

    public class Solution {

       public ListNode sortList(ListNode head) {
        if(head == null){
            return null;
        }
        
        int length = ListLength(head);
        if(length == 1){
            return head;
        }
       
        int middle = (int)Math.floor(ListLength(head)/2); 
        
        ListNode temp = head;
        ListNode leftHead = head;
        for(int i=1; i< middle; i++){
            temp = temp.next;
        }
        ListNode rightHead = temp.next;
        temp.next = null;  
        
         
        ListNode left = sortList(leftHead); 
        ListNode right = sortList(rightHead);
        ListNode rs= merge( left, right);
        return rs;
    }
    
    
    
    public ListNode merge(ListNode left, ListNode right){ 
        ListNode leftTemp = left;
        ListNode rightTemp = right;
        ListNode result;
        if(leftTemp.val < rightTemp.val){ 
        	System.out.println(leftTemp.val);
            result = leftTemp;
            leftTemp = leftTemp.next;
        }else{  
            result = rightTemp;
            rightTemp = rightTemp.next;
        }
        
        ListNode temp = result;
        while(leftTemp != null && rightTemp != null){
            if(leftTemp.val < rightTemp.val){ 
                temp.next = leftTemp;
                temp = temp.next;
                leftTemp = leftTemp.next;
            }else{ 
                temp.next = rightTemp;
                temp=temp.next;
                rightTemp = rightTemp.next;
            }
        }
        
        if(leftTemp != null){
            temp.next  = leftTemp;
        }
        if(rightTemp != null){ 
            temp.next = rightTemp;
        } 
        return result;
    }
    
    
    public int ListLength(ListNode head){
        int i = 1;
        ListNode temp = head;
        while(temp.next != null){
            i += 1;
            temp = temp.next;
        }
        return i;
    }
    

    }


Log in to reply
 

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