Java - with use LinkedList as "Stack" (Stack.class in java is thread-safe)


  • 0
    N
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            if (l1 == null) return l2;
            if (l2 == null) return l1;
            
            LinkedList<ListNode> q1 = calc(l1);
            LinkedList<ListNode> q2 = calc(l2);
            
            return q1.size() >= q2.size() ? result(q1, q2) : result(q2, q1);
        }
        
        private LinkedList<ListNode> calc(ListNode node) {
            LinkedList<ListNode> queue = new LinkedList<>();
            while (node != null) {
                queue.add(node);
                node = node.next;
            }
            return queue;
        }
        
        private ListNode result (LinkedList<ListNode> target, LinkedList<ListNode> source) {
            int extra = 0;
            ListNode last = null;
            ListNode l1 = null;
            while (target.size() > 0) {
                l1 = target.removeLast();
                
                int sum = l1.val + extra + (source.size() > 0 ? source.removeLast().val : 0);
                extra = sum / 10;
                l1.val = sum % 10;
                last = l1;
            }            
            
            if(extra > 0) {
                ListNode result = new ListNode(extra);
                result.next = last;
                return result;
            } else {
                return last;
            }
        }
    }
    
    

Log in to reply
 

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