gold-2-5


给定两个用链表表示的整数,每个节点包含一个数位。

这些数位是反向存放的,也就是个位排在链表首部。

编写函数对这两个整数求和,并用链表形式返回结果。

示例:

输入:(7 -> 1 -> 6) + (5 -> 9 -> 2),即617 + 295
输出:2 -> 1 -> 9,即912

进阶:思考一下,假设这些数位是正向存放的,又该如何解决呢?

示例:

输入:(6 -> 1 -> 7) + (2 -> 9 -> 5),即617 + 295
输出:9 -> 1 -> 2,即912

//leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }

        int l1Len = 0;
        int l2Len = 0;
        ListNode temp = l1;
        while (temp != null) {
            l1Len++;
            temp = temp.next;
        }
        temp = l2;
        while (temp != null) {
            l2Len++;
            temp = temp.next;
        }

        int len = 0;
        int carry = 0;
        ListNode l = null;
        ListNode otherL = null;
        ListNode head = null;

        if (l1Len > l2Len) {
            len = l1Len;
            l = l1;
            otherL = l2;
            head = l1;
        } else {
            len = l2Len;
            l = l2;
            otherL = l1;
            head = l2;
        }

        for (int i = 0; i < len; i++) {
            if (otherL != null) {
                l.val += otherL.val;
                otherL = otherL.next;
            }
            l.val += carry;
            if (l.val > 9) {
                l.val -= 10;
                carry = 1;
            } else {
                carry = 0;
            }
            if (i == len - 1 && carry == 1) {
                ListNode last = new ListNode();
                last.val = 1;
                l.next = last;
                break;
            }
            l = l.next;
        }

        return head;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !