addition of list using stack


  • 0
    T

    ListNode curr1 = l1, curr2 = l2;
    Stack<Integer> s1 = new Stack<Integer>();
    Stack<Integer> s2 = new Stack<Integer>();
    int i = 0;
    while(curr1 != null)
    {
    s1.push(curr1.val);
    curr1 = curr1.next;
    }

        while(curr2 != null)
        {
            s2.push(curr2.val);
            curr2 = curr2.next;
        }
        
        int sum = 0; 
        Stack<Integer> result = new Stack<Integer>();
        while(!s1.empty() || !s2.empty())
        {
             if(!s1.empty())
             {
                 sum += s1.pop();
             }
            
            if(!s2.empty())
            {
                sum += s2.pop();
            }
            result.push(sum % 10);
            
            sum = (sum / 10);   
        }
        if (sum == 1)
        {
            result.push(sum);
        }
        ListNode head = new ListNode(0);
        ListNode curr = head;
        while(!result.empty())
        {
            ListNode val = new ListNode(result.pop());
            curr.next = val;
            curr = curr.next;
        }
        
        return head.next;

Log in to reply
 

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