accepted java solution


  • 0
    K

    public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        Stack<Integer> s1 = new Stack<>();
        Stack<Integer> s2 = new Stack<>();
        while(l1!=null||l2!=null){
            if(l1!=null){
                s1.push(l1.val);
                l1 = l1.next;
            }
            if(l2!=null){
                s2.push(l2.val);
                l2 = l2.next;
            }
        }
        int cf = 0;
        ListNode dummy = new ListNode(-1);
        ListNode prev = null;
        while(!s1.empty() || !s2.empty() || cf==1){
            int sum = (s1.empty()?0:s1.pop()) + (s2.empty()?0:s2.pop()) + cf;
            cf = sum>=10 ? 1:0;
            ListNode ln = new ListNode(sum%10);
            ln.next = prev;
            dummy.next = ln;
            prev = ln;
        }
        return dummy.next;
    }
    

    }


Log in to reply
 

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