Run Code Status: Runtime Error,but it is correct at local runtime environment


  • 0
    D

    public class ListNode {
    public int val;
    public ListNode next;
    public ListNode(int x) { val = x; }
    }

    class Solution {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    
        int toward=0;
    
        ListNode p1=l1;
        ListNode p2=l2;
        ListNode p=null;
        ListNode r=null;
    
        while(true){
    
            if(p1==null&&p2==null){
                if(toward>0){
                    ListNode p3=new ListNode(1);
                    p.next=p3;
                }
                break;
            }
    
            int plusVal=toward;
            toward=0;
            ListNode p3=new ListNode(0);
            int val=0;
            if(p1!=null&&p2!=null){
                val=p1.val+p2.val+plusVal;
            }else if(p1==null&&p2!=null){
                val=p2.val+plusVal;
            }else if(p1!=null&&p2==null){
                val=p1.val+plusVal;
            }
    
            toward=val/10;
         
            p3.val=val%10;
    
            if(p==null){
                r=p=p3;
            }else{
                p.next=p3;
                p=p.next;
            }
    
            if(p1!=null){
                p1=p1.next;
            }
            if(p2!=null){
                p2=p2.next;
            }
    
        }
        return r;
    }
    
    public static void main(String[] args) {
        Solution solution=new Solution();
        ListNode l1=new ListNode(2);
        l1.next=new ListNode(4);
        l1.next.next=new ListNode(3);
    
        ListNode l2=new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next=new ListNode(9);
        ListNode r = solution.addTwoNumbers(l1, l2);
        while (r!=null){
            System.out.println(r.val);
            r=r.next;
        }
    
    }
    

    }


Log in to reply
 

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