Java Code: Runtime error on {} input doesn't make sense to me.


  • 1
    R

    My code works fine in eclipse when I test it on the {} empty input but for some reason that I can't figure out the online judge is saying runtime error on the {} empty input.

    Can you find the problem? If so, please share. Many thanks in advance.

    Here is my code:

    public class Solution {
    	
    	public ListNode sortList(ListNode head) {
            if(head == null || head.next == null){
                return head;
            }
            int length = getLength(head);
            //split list
            ListNode head2 = head.next;
            ListNode head2pre = head;
            for(int i = 1; i < length/2; i++){
                head2pre = head2;
                head2 = head2.next;
            }
            //end first list
            head2pre.next = null;
            ListNode result = merge(sortList(head), sortList(head2));
            return result;
        }
        
        private ListNode merge(ListNode a, ListNode b){
            if(a == null){
                return b;
            }
            if(b == null){
                return a;
            }
            ListNode runner = a;
            ListNode runnerPre = null;
            while(runner != null && b != null){
                if(runner.val < b.val){
                    runnerPre = runner;
                    runner = runner.next;
                }
                else{
                	if(runnerPre != null){
                        runnerPre.next = new ListNode(b.val);
                        runnerPre.next.next = runner;	
                        b = b.next;
                        runnerPre = runner;
                        runner = runner.next;
                	}
                	else{
                		runnerPre = new ListNode(b.val);
                		runnerPre.next = a;
                		a = runnerPre;
                		b = b.next;
                	}
                }
            }
            if(runner == null){
                runnerPre.next = b;
            }
            return a;
        }
        
        private int getLength(ListNode head){
            if(head == null){
                return 0;
            }
            ListNode runner = head;
            int length = 1;
            while(runner.next != null){
                length++;
                runner = runner.next;
            }
            return length;
        }
    }

  • 0
    R

    Same problem here. Couldn't make head or tail of it


Log in to reply
 

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