Brilliant Java solution


  • 1
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
         Stack<Integer> s1=new Stack();
         Stack<Integer> s2=new Stack();
         while(l1!=null){
             s1.push(l1.val);
             l1=l1.next;
         }
          while(l2!=null){
             s2.push(l2.val);
             l2=l2.next;
         }
         int c=0,s=0;
         ListNode current=null;
         
         while(!s1.isEmpty()||!s2.isEmpty()){
             
             s=(s1.isEmpty()?0:s1.pop()) +( s2.isEmpty()?0:s2.pop()) + c;
             c=s/10;
             s=s%10;
             ListNode p=new ListNode(s);
             p.next=current;
             current=p;
         }
         if(c>0){
              ListNode p=new ListNode(c);
             p.next=current;
             current=p;
         }
          return current;  
            
        }
    

Log in to reply
 

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