Java Solutions using two stacks


  • 0
    D
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            Stack<Integer> s1 = new Stack<Integer>();
            Stack<Integer> s2 = new Stack<Integer>();
            ListNode res = null;
            while (l1 != null || l2 != null) {
                if (l1 != null) {
                    s1.push(l1.val);
                    l1 = l1.next;
                }
                else {
                    s2.push(l2.val);
                    l2 = l2.next;
                }
            }
            int a = 0, b = 0, carry = 0, sum = 0;
            while (!s1.isEmpty() || !s2.isEmpty() || carry != 0) {
                a = !s1.isEmpty()? s1.pop() : 0 ;
                b = !s2.isEmpty()? s2.pop() : 0 ;
                sum = a + b + carry;
                ListNode temp = new ListNode(sum % 10);
                temp.next = res;
                res = temp;
                carry = sum / 10;
            }
            return res;
    }

Log in to reply
 

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