shorter solution by stack


  • 0
    X
    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;
        }
    
        ListNode pre = null;
        int curry = 0;
        while (stack1.size() > 0 || stack2.size() > 0 || curry > 0) {
            int sum = (stack1.size() == 0 ? 0 : stack1.pop()) + (stack2.size() == 0 ? 0 : stack2.pop()) + curry;
            ListNode cur = new ListNode(sum % 10);
            cur.next = pre;
            pre = cur;
            curry = sum / 10;
        }
    
        return pre;
    }
    

Log in to reply
 

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