Please help with MLE


  • 0
    A
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode partition(ListNode head, int x) {
            ListNode firstHead = null; 
            ListNode firstEnd = null;
            
            ListNode secondHead = null;
            ListNode secondEnd = null; 
            
            ListNode current = head;
            
           while(current!=null){
               if(current.val < x){
                   if(firstHead == null){
                       firstHead = current;
                       firstEnd = firstHead;
                   }else{
                       firstEnd.next = current;
                       firstEnd = current;
                   }
               }else{
                   if(secondHead == null){
                       secondHead = current;
                       secondEnd = secondHead;
                   }else{
                       secondEnd.next = current; 
                       secondEnd = current; 
                   }
               }
               current = current.next;
           }
           
           if(firstHead == null) return secondHead;
           
           firstEnd.next = secondHead; 
           return firstHead; 
        }
    }

  • 1
    Y

    You forgot to set the end of the list to null, and it ends up a circular list.


Log in to reply
 

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