Java, clean code, using stack, O(n)


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

Log in to reply
 

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