问题描述
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记录两位数之和,carry求余的结果作为个位数,再对carry除完之后的结果返还给carry,再下一次计算的时候,刚好作为进位,存储进去。这个方法遇到第二次了,值得借鉴。
问题解惑
- temp作用是?全程没有对res进行操作,为什res最后会有结果?
因为除了基本类型之外,所有new一个对象,实际上都指向的是该对象的地址。所以res实际上指向的是一个地址,而res = temp,所以temp和res指向了相同的地址,对temp操作实际上就是对res进行了操作。 - temp.next = new ListNode(carry % 10)和return res.next中,为什么第一次存储存在了节点的第二个?
因为一开始ListNode temp = new ListNode(0)对数组进行初始化,这个步骤是必须的。所以实际上节点第一个值是0,已经被占了,所以直接从节点第二个开始存,最后return也直接从第二个节点开始返回,刚好就是结果。
代码
/**
* 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) {
//corner case
if(l1 == null && l2 == null) return null;
//to store the sum of two digits
int carry = 0;
ListNode res;
ListNode temp = new ListNode(0);
res = temp;
while(l1 != null || l2 != null || carry != 0){
//process adding of two digits
if(l1 != null){
carry += l1.val;
l1 = l1.next;
}
if(l2 != null){
carry += l2.val;
l2 = l2.next;
}
//get the sum of two digits and carry still fuction as itself
temp.next = new ListNode(carry % 10);
temp = temp.next;
carry /= 10;
}
return res.next;
}
}
复杂度探究
时间复杂度:O(n)
空间复杂度:O(n)