Java Solution by Reversing LinkedList beating 100%


  • 0
    B

    Reversing the LinkedList might not be the best idea for interview. Surprisingly, the performance improved way a lot after changed the ternary operator return statement to if block. Maybe ternary operator could make the code concise, instead of performance.

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            Stack<Integer> s1 = new Stack<>();
            Stack<Integer> s2 = new Stack<>();
            
            while (l1 != null){
                s1.push(l1.val);
                l1 = l1.next;
            }
            while (l2 != null){
                s2.push(l2.val);
                l2 = l2.next;
            }
            int carry = 0; 
            ListNode dummy = new ListNode(0);
            while (!s1.empty() || !s2.empty()){
                int x = !s1.empty() ? s1.pop() : 0;
                int y = !s2.empty() ? s2.pop() : 0;
                int sum = x + y + carry;
                carry = sum / 10;
                dummy.val = sum % 10;
                ListNode head = new ListNode(carry);
                // keep adding the right sublist to the head
    	    head.next = dummy;
                dummy = head;
    
    		}
    	if (carry > 0){
                dummy.val = carry;
                return dummy;
            }else{
                return dummy.next;
            }
        }
    

Log in to reply
 

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