Using two stack, insert next node ahead


  • 0
    W
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stack<Integer> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();
        while(l1 != null) {
            stack1.push(l1.val);
            l1 = l1.next;
        }
        
        while(l2 != null) {
            stack2.push(l2.val);
            l2 = l2.next;
        }
        
        int carry = 0;
        ListNode p = null;
    
       while(!stack1.isEmpty() || !stack2.isEmpty() || carry != 0) {
            int val = carry;
            if(!stack1.isEmpty()) {
                val += stack1.pop();
            }
            if(!stack2.isEmpty()) {
                val += stack2.pop();
            }
            ListNode node = new ListNode(val%10);
            node.next = p;
            carry = val / 10;
            p = node;
        }
        
        return p;
    }

Log in to reply
 

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