AC follow up Java


  • 1
    H

    the thought is every time when you need a reverse order, rather than reverse it directly, you should think about using stack, whose nature is actually used to reverse. Below is the code:

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            Stack<ListNode> s1 = new Stack<>();
            Stack<ListNode> s2 = new Stack<>();
            Stack<ListNode> s3 = new Stack<>();
            
            while (l1 != null) {
                s1.push(l1);
                l1 = l1.next;
            }
            while (l2 != null) {
                s2.push(l2);
                l2 = l2.next;
            }
            
            int carry = 0;
            while (!s1.isEmpty() || !s2.isEmpty()) {
                int val1 = s1.isEmpty() ? 0 : s1.pop().val;
                int val2 = s2.isEmpty() ? 0 : s2.pop().val;
                
                int val = val1 + val2 + carry;
                ListNode node = new ListNode(val % 10);
                carry = val / 10;
                s3.push(node);
            }
            if (carry == 1) s3.push(new ListNode(1));
            ListNode dummy = new ListNode(0);
            ListNode node = dummy;
            while (!s3.isEmpty()) {
                node.next = s3.pop();
                node = node.next;
            }
            
            return dummy.next;
        }
    

Log in to reply
 

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