Run time error for one test case.

  • 0

    Hi, I am having run time error, but I can't figure out what the problem is, because it runs fine on my local environment.

    Submission Result: Runtime Error

    Last executed input: {3,2,3,3,3,1,3,1,3,3,1,1,3,3,2,1,1,1,1,2,1,1,2,1,2,1,3,2,...........

    public class Solution {
        public ListNode sortList(ListNode head) {
             ListNode mid, temp;
            if(head == null || == null)
                return head;
            //Find the middle node
            mid = middleNode(head);
            //create two list, by breaking from the middle
            temp = mid;
            mid =;
   = null;
            //call mergeSort recursively
            head = sortList(head);
            mid = sortList(mid);
            //merge the two sorted list and return 
            return mergeList(head, mid);
        private ListNode middleNode(ListNode head){
            ListNode currentNode1, currentNode2;
            //check if there is 0 or 1 in the list
            if(head == null || == null)
                return head;
            //start the pointer
            currentNode1 = head;
            currentNode2 = head;
            //move till fast pointer reaches the end
            while( != null){
                //move fast pointer by one
                currentNode2 =;
                // check if end has reached or not
                if( == null)
                    return currentNode1;
                //another move for fast pointer and a move for slow
                currentNode2 =;
                currentNode1 =;
    	    //return the reference to the middle node
            return currentNode1;
        private ListNode mergeList(ListNode node1, ListNode node2){
            ListNode result = null;
            //check if first list is empty	
    	    if(node1 == null)
    	        return node2;
            //check if second list is empty
    	    else if(node2 == null)
    	        return node1;
            //compare the two list and recursively call the method for merge
    	    else if(node1.val <= node2.val){
    	        result = node1;
    = mergeList(, node2);
    	    else if(node1.val > node2.val){
    	        result = node2;
    = mergeList(node1,;
    	//return the head
    	return result;

  • 1

    My previous solution had the same problem too. Using iterative solution to merge two lists can solve the problem.

Log in to reply

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