leetcode2 Add Two Numbers
问题描述
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,l1.length < l2.length; 例2, l1=[ ], l2=[1,2];例3 l1=[1, 2], l2 = [1]。当我们计算上图两个链表之和的时候,4 + 6 = 10,这种情况下,我们设置current = 0, 同时carry = 1指向下一个。carry的值必须为0或者1,因为最大数的可能值就是9 + 9 + 1 = 19。
实现步骤
- 将当前节点初始化为返回列表的dummy head
- 将carry初始化为0
- 初始化p, q分别为l1和l2的头
- 循环列表l1以及l2,直到计算全部数据
- 设置x为节点p的值,如果p到达l1的结尾,则设置为0
- 设置y为节点q的值,如果q到达l2的结尾,则设置为0
- 设置sum = x + y + carry
- 更新carry = sum/10
- 创建一个新的节点,放入的数字是(sum % 10)得到的个位数字,并且设置其为当前节点的下一个,然后将当前节点推进到下一个。
- 将p和q提前
- 检查carry 是否等于1,如果是则将数字1追加到返回list
- 返回伪头到下一个节点
代码实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 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);
curr = curr.next;
if(p != null)
p = p.next;
if(q != null)
q = q.next;
}
if(carry > 0){
curr.next = new ListNode(carry);
}
return dummyHead.next;
}
}