RunTime Error for the Last executed input:{0}, {0}. Can someone help me? I can not find the bug


  • 0
    D
        public class Solution {
       public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode head  = new ListNode(-1); //head node
            ListNode p = head; //working pointer
            int carrier = 0;
            while(l1!=null || l2!=null){
            	int num1,num2;
            	if(l1!=null)
            	   num1 = l1.val;
            	else
            		num1=0;
            	if(l2!=null)
            	   num2 = l2.val;
            	else
            		num2 = 0;
            	
            	int sum = num1+num2+carrier;
            	if(sum >= 10){
            		sum = sum % 10;
            		carrier = 1;
            	}else{
            		carrier = 0;
            	}
            	ListNode node = new ListNode(sum);
            	p.next = node;
            	p = p.next;
            	
            	if(l1 !=null)
            	   l1 = l1.next;
            	if(l2 !=null)
            	   l2 = l2.next;
            }
            
            if(carrier == 1){//last carrier
                ListNode node = new ListNode(1);
                p.next = node;
                p = p.next;
            }
            
            head = head.next;//skip the first node(-1)
            return head;
        }
    }
    
    
    class ListNode {
    	int val;
    	ListNode next;
    
    	public ListNode(int x) {
    		val = x;
    		next = null;
    	}
    	
    	public ListNode(int x,ListNode node){
    		val = x;
    		next = node;
    	}
    }

  • 0
    D

    I delete the definition of class ListNode, then it works. I think it is because of the duplicated definition of ListNode.


Log in to reply
 

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