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.
题目分析:单链表操作,数字相加
算法分析:
要注意进位问题,记carry为进位,两个数字相加,进位不是0就是1,初始化carry为0,不断更新它的值。另外,可以设一个虚拟的头结点,如果不设虚拟的头结点,就要分几种情况初始化头结点的值。第一种是,链表 l1,l2 的长度不一样长;第二种是,有一个链表为空链表;第三种,也是最容易忽视的一种是,最高位的进位,比如 l1 = [ 9,9 ] , l2 = [ 1 ],最高位进位后的1是要写在结果里一起返回的。这里还是选择虚拟头结点的算法,以简化代码。
算法设计:
/**
* 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) {
ListNode dummyHead = new ListNode(0); // 虚拟头结点
ListNode p = l1, q = l2, curr = dummyHead; // 初始化 l1 , l2 , curr
int carry = 0; // 进位初始化为0
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10; // 更新
curr.next = new ListNode(sum % 10); // 结果链表中创建一个新结点,存放 sum % 10 的值
curr = curr.next;
if (p != null)
p = p.next;
if (q != null)
q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);// 如果carry=1,用新结点存放
}
return dummyHead.next;
}
}