You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order 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.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

难度:medium

题目:
给定两个非空且元素非负的链表。链表中的数字以逆序排列且每个结点只含一个一位数。使两个数相加并反回其结果。
你可以认为两个数字都不以0开头。自然数0除外。

思路:
1.设置头结点简化操作。
2.从前向后遍历相加。

Runtime: 21 ms, faster than 93.90% of Java online submissions for Add Two Numbers.

/**
 * 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) {
        int carry = 0;
        ListNode head = new ListNode(0), tail = head;
        while(l1 != null || l2 != null || carry != 0) {
            int val = carry;
            if (null != l1) {
                val += l1.val;
                l1 = l1.next;
            }
            if (null != l2) {
                val += l2.val;
                l2 = l2.next;
            }
            carry = val / 10;
            ListNode node = new ListNode(val % 10);
            tail.next = node;
            tail = node;
        }
        
        return head.next;
    }
}

linm
1 声望4 粉丝

〜〜〜学习始于模仿,成长得于总结〜〜〜