Loading

2. [链表]两数相加

2. 两数相加

// 执行用时:2 ms, 在所有 Java 提交中击败了99.89%的用户
// 内存消耗:40 MB, 在所有 Java 提交中击败了94.26%的用户
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode result = new ListNode((l1.val + l2.val) % 10);
        int jinwei = (l1.val + l2.val) / 10;
        l1 = l1.next;
        l2 = l2.next;
        while (l1 != null && l2 != null) {
            int current = l1.val + l2.val + jinwei;
            ListNode temp = result;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = new ListNode(current % 10);
            jinwei = current / 10;
            l1 = l1.next;
            l2 = l2.next;
        }
        while (l1 != null) {
            int current = l1.val + jinwei;
            ListNode temp = result;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = new ListNode(current % 10);
            jinwei = current / 10;
            l1 = l1.next;
        }
        while (l2 != null) {
            int current = l2.val + jinwei;
            ListNode temp = result;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = new ListNode(current % 10);
            jinwei = current / 10;
            l2 = l2.next;
        }
        if (jinwei == 1) {
            ListNode temp = result;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = new ListNode(1);
        }
        return result;
    }
}
posted @ 2020-10-21 22:40  上海井盖王  阅读(60)  评论(0)    收藏  举报