445. Add Two Numbers II

Medium
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

Solution:
use two stacks

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stack<ListNode> s1 = new Stack<ListNode>();
        Stack<ListNode> s2 = new Stack<ListNode>();
        ListNode node1 = l1;
        ListNode node2 = l2;
        while(node1!=null){
            s1.push(node1);
            node1 = node1.next;
        }
        while(node2!=null){
            s2.push(node2);
            node2 = node2.next;
        }
        int num1 = 0;
        int num2 = 0;
        int sum = 0;
        int carry = 0;
        ListNode node = null;
        ListNode pre = null;
        while(!s1.isEmpty() ||  !s2.isEmpty()){
            num1 = s1.isEmpty()?0:s1.pop().val;
            num2 = s2.isEmpty()?0:s2.pop().val;
            sum = num1 + num2 + carry;
            if(sum/10 > 0){
                carry = 1;
            }else {
             carry = 0;
            }
            node = new ListNode(sum%10);
            node.next = pre;
            pre = node;//don't forget to assign pre variable.
        }
        test case : [5],[5]
        if(carry == 1) {
         
         node = new ListNode(1);
         node.next = pre;
        }
        return node;
    }


Comments

Popular posts from this blog

MockInterview:785. Is Graph Bipartite?

geeksforgeeks:findFind zeroes to be flipped so that number of consecutive 1’s is maximized

94.Binary Tree Inorder Traversal