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.
你可以假设两个数不可能为0,除了本身是0
即 最高位不为0
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
1.只需要计算当前位和进位即可
2. 首位为 0
3. 如果一边加完就把另一边剩余的输出
4.考虑进位的问题 5 + 5 —— 10 最后 一个进位 需要考虑
5. 将题目考虑错误 将 0 的定义错误 [0,0,0,1] 是正确的
6. 将flag 的考虑需要完善
/**
* 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 temp1 = l1;
ListNode temp2 = l2;
ListNode sum = null;
ListNode sumTemp = null;
if(temp1.val == 0 && temp1.next == null){// temp1 为空 直接返回 temp2 另 temp2 同时为0 直接返回 0
sum = temp2;
}else{
if(temp2.val == 0 && temp2.next == null){ // temp2 为空 直接返回 temp1
sum = temp1;
}else{ //同时不为 0
int flag = 0;
sumTemp = new ListNode((temp1.val + temp2.val) % 10);
sum = sumTemp;
flag = (temp1.val + temp2.val) / 10;
while( temp1.next!=null && temp2.next !=null){
temp1 = temp1.next;
temp2 = temp2.next;
sumTemp.next = new ListNode((temp1.val + temp2.val + flag) % 10);
flag = (temp1.val + temp2.val + flag) / 10;
sumTemp = sumTemp.next;
}
while(temp1.next == null && temp2.next != null){
temp2 = temp2.next;
sumTemp.next = new ListNode((temp2.val + flag) % 10);
flag = (temp2.val + flag) / 10;
sumTemp = sumTemp.next;
}
while(temp1.next != null && temp2.next == null){
temp1 = temp1.next;
sumTemp.next = new ListNode((temp1.val + flag) % 10);
flag = (temp1.val + flag) / 10;
sumTemp = sumTemp.next;
}
if(flag == 1){
sumTemp.next = new ListNode(flag);
}
}
}
return sum;
}
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0); //初始化为返回的样子
ListNode p = l1, q = l2, curr = dummyHead;//p q 初始化 curr 当前节点
int carry = 0; // carry 进位初始化
while (p != null || q != null) { // p q 同时不为空时
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;
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/add-two-numbers/solution/liang-shu-xiang-jia-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
复杂度分析
时间复杂度:O(max(m,n)),假设 m 和 n 分别表示 l1 和 l2 的长度,上面的算法最多重复 max(m,n) 次。
空间复杂度:O(max(m,n)), 新列表的长度最多为 \max(m,n) + 1max(m,n)+1。
本题做麻烦了,思路不清晰 把初始化和算法混在一起,分情况有些问题,应总体看整个题目。
初始化 --》 算法 --》 输出