Clean Java AC two stack solution


  • 0
    W
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            if (l1 == null || (l1.next == null && l1.val == 0)) return l2;
            if (l2 == null || (l2.next == null && l2.val == 0)) return l1;
            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 carry = 0;
            ListNode prev = null;
            while (!s1.isEmpty() || !s2.isEmpty()) {
                int n1 = s1.isEmpty() ? 0 : s1.pop();
                int n2 = s2.isEmpty() ? 0 : s2.pop();
                int sum = n1 + n2 + carry;
                carry = sum / 10;
                ListNode curr = new ListNode(sum % 10);
                curr.next = prev;
                prev = curr;
            }
            if (carry == 0) return prev;
            ListNode head = new ListNode(1);
            head.next = prev;
            return head;
        }
    

Log in to reply
 

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