Java Accepted Solution using queues


  • 0
    S

    '''
    public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    Queue<Integer> q1 = new LinkedList<>();
    Queue<Integer> q2 = new LinkedList<>();

        while(l1 != null){
            q1.add(l1.val);
            l1 = l1.next;
        }
        while(l2 != null){
            q2.add(l2.val);
            l2 = l2.next;
        }
        
        ListNode link = new ListNode(0);
        ListNode tail = link;
        int sum = 0;
        while(!q1.isEmpty() || !q2.isEmpty()){
            if(!q1.isEmpty()) sum+= q1.poll();
             if(!q2.isEmpty()) sum+= q2.poll();
             link.val = sum%10;
             ListNode head = new ListNode(sum/10);
             link.next = head;
             link = head;
             sum = sum/10;
             
            
        }
        if(link.val == 0){
            ListNode x = tail;
            while(x.next.next != null){
                x= x.next;
            }
            x.next = null;
            }return tail;
    }
    

    }
    '''


Log in to reply
 

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