A simple Java solution


  • 0
    L

    This problem may be solved using Stacks, or using arrays where the traversal is done in the reverse. Nonetheless, here is the solution using stacks.

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            Stack<Integer> s1 = new Stack<Integer>();
            Stack<Integer> s2 = new Stack<Integer>();
            
            while(l1!=null || l2!=null) {
                if(l1!=null) {
                    s1.push(l1.val);
                    l1 = l1.next;
                }
                
                if(l2!=null) {
                    s2.push(l2.val);
                    l2 = l2.next;
                }
            }
            
            int carry = 0;
            Stack<Integer> res = new Stack<Integer>();
          while(!s1.isEmpty() || !s2.isEmpty() || carry>0) {
                int sum = carry;
                if(!s1.isEmpty()) {
                    sum += s1.pop();
                }
                
                if(!s2.isEmpty()) {
                    sum += s2.pop();
                }
                res.push(sum%10);
                carry = sum/10;
            }
            
            
            ListNode dummyHead = new ListNode(-1);
            ListNode it = dummyHead;
            while(!res.isEmpty()) {
                it.next = new ListNode(res.pop());
                it = it.next;
            }
            
            return dummyHead.next;
        }
    }
    

Log in to reply
 

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