LeetCode 445. Add Two Numbers II

来源:互联网 发布:我要请运营淘宝的 编辑:程序博客网 时间:2024/06/05 23:03

原题网址:https://leetcode.com/problems/add-two-numbers-ii/

You are given two linked lists representing two non-negative numbers. 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

方法:如果不能反转原链表的话,可以反转结果链表。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    private int length(ListNode node) {        if (node == null) return 0;        return 1 + length(node.next);    }    private ListNode reverse(ListNode node) {        if (node == null) return null;        if (node.next == null) return node;        ListNode prev = node;        ListNode curr = node.next;        prev.next = null;        while (curr != null) {            ListNode next = curr.next;            curr.next = prev;            prev = curr;            curr = next;        }        return prev;    }    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        int len1 = length(l1);        int len2 = length(l2);        int len = Math.max(len1, len2);        ListNode start = new ListNode(0);        ListNode node = start;        for(int i = 0; i < len; i++) {            node.next = new ListNode(0);            node = node.next;            if (i + len1 >= len) {                node.val += l1.val;                l1 = l1.next;            }            if (i + len2 >= len) {                node.val += l2.val;                l2 = l2.next;            }        }        start.next = reverse(start.next);        node = start;        int carry = 0;        while (node.next != null) {            node = node.next;            node.val += carry;            carry = node.val / 10;            node.val %= 10;        }        if (carry != 0) {            node.next = new ListNode(carry);        }        start.next = reverse(start.next);        return start.next;    }}


0 0
原创粉丝点击