Concise Java O(n) using reverse


  • 0
    Y
    public class Solution {
        private ListNode reverse(ListNode node) {
            ListNode prev = null, temp = null;
            while (node != null) {
                temp = node.next;
                node.next = prev;
                prev = node;
                node = temp;
            }
            return prev;
        }
        
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            l1 = reverse(l1);
            l2 = reverse(l2);
            int carry = 0;
            ListNode dummy = new ListNode(0);
            ListNode cur = dummy;
            while (l1 != null || l2 != null || carry != 0) {
                int sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry;
                cur.next = new ListNode(sum % 10);
                carry = sum / 10;
                cur = cur.next;
                l1 = l1 == null ? l1 : l1.next;
                l2 = l2 == null ? l2 : l2.next;
            }
            return reverse(dummy.next);
        }
    }
    

Log in to reply
 

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