LeetCode-Microsoft-Add Two Numbers II Add Two Numbers Reverse Linked List

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

It can be regarded as a synthesis of Add Two Numbers and Reverse Linked List . First, reverse the add one by one, and finally reverse the result.

Time Complexity: O(n). reverse O(n), add O(n).

Space: O(1). reverse O(1), add O(1).

AC Java:

/**
 * 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;
        }
        l1 = reverseList(l1);
        l2 = reverseList(l2);
        
        ListNode cur = l1;
        int len1 = 0;
        while(cur != null){
            len1 ++ ;
            cur = cur.next;
        }
        
        cur = l2;
        int len2 = 0;
        while(cur != null){
            len2++;
            cur = cur.next;
        }
        
        ListNode dummy = new ListNode(0);
        if(len1 > len2){
            dummy.next = l1;
        }else{
            dummy.next = l2;
        }
        cur = dummy;
        int carry = 0;
        
        while(l1 != null || l2 != null){
            if(l1 != null){
                carry += l1.val;
                l1 = l1.next;
            }
            if(l2 != null){
                carry += l2.val;
                l2 = l2.next;
            }
            cur.next.val = carry%10;
            cur = cur.next;
            carry /= 10;
        }
        if(carry != 0){
            cur.next = new ListNode(1);
        }
        
        ListNode nxt = dummy.next;
        ListNode newHead = reverseList(nxt);
        nxt.next = null;
        return newHead;
    }
    private ListNode reverseList(ListNode head){
        if(head == null || head.next == null){
            return head;
        }
        ListNode tail = head;
        ListNode cur = head;
        ListNode pre;
        ListNode temp;
        while(tail.next != null){
            pre = cur;
            cur = tail.next;
            temp = cur.next;
            cur.next = pre;
            tail.next = temp;
        }
        return cur;
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325065367&siteId=291194637