1. 程式人生 > 其它 >445. 兩數相加 II

445. 兩數相加 II

字。將這兩數相加會返回一個新的連結串列。

你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/add-two-numbers-ii
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

class Solution {

    private ListNode reverse(ListNode head) {
        ListNode pre = null, cur = head, next;
        while (cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

    private ListNode add(ListNode l1, ListNode l2) {
        ListNode newHead = new ListNode(), tail = newHead;
        int add = 0;
        while (l1 != null && l2 != null) {
            int num = l1.val + l2.val + add;
            tail.next = new ListNode(num % 10);
            tail = tail.next;
            add = num / 10;

            l1 = l1.next;
            l2 = l2.next;
        }

        while (l1 != null) {
            int num = l1.val + add;
            tail.next = new ListNode(num % 10);
            tail = tail.next;
            add = num / 10;
            l1 = l1.next;
        }

        while (l2 != null) {
            int num = l2.val + add;
            tail.next = new ListNode(num % 10);
            tail = tail.next;
            add = num / 10;
            l2 = l2.next;
        }

        if (add == 1) {
            tail.next = new ListNode(1);
            tail = tail.next;
        }

        return reverse(newHead.next);
    }

    private ListNode trim(ListNode head) {
        if (head == null) {
            return head;
        }
        while (head.next != null && head.val == 0) {
            head = head.next;
        }
        return head;
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        return trim(add(reverse(l1), reverse(l2)));
    }
}


class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

心之所向,素履以往 生如逆旅,一葦以航