# 2. Add Two Numbers

XAMPP下载 174浏览

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.

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;
}
}