Java Solution by Reversing LinkedList beating 96%


  • 3
    W
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode n1 = reverse(l1);
            ListNode n2 = reverse(l2);
            int carry = 0;
            ListNode temp = n1;
            ListNode pre = n1;
            while(n1!= null || n2 != null || carry != 0){
                int v1 = n1 == null? 0: n1.val;
                int v2 = n2 == null? 0: n2.val;
                if(n1 == null){
                    n1 = new ListNode((v1+v2+carry) % 10);
                    pre.next = n1;
                }else{
                    n1.val = (v1+v2+carry) % 10;
                }
                carry = (v1+v2+carry)/10;
                pre = n1;
                n1 = n1 == null? null : n1.next;
                n2 = n2 == null? null : n2.next;
            }
            return reverse(temp);
        }
        public ListNode reverse(ListNode head){
            ListNode newHead = null;
            while(head != null){
                ListNode next = head.next;
                head.next = newHead;
                newHead = head;
                head = next;
            }
            return newHead;
        }
    

  • 0

    Code is elegant and it is indeed faster!


  • 0
    A

    @WrenChan please explain what is the use of pre,thanks


Log in to reply
 

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