题目描述
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
个人思路及解法(思路与官方相同)
最开始想的是直接把链表转化为数字,相加之后再转回链表。
但是问题是,链表表示的数字有可能非常大,根本存不下,所以放弃了。
之后准备循环链表对应的数字相加,直接生成新链表。
单独用一个变量来记录进位,相加时直接加进去
循环过程中,循环完的链表,计算时当前位当做0
其中要注意的是,假如两条链表最后一位相加>10,需要再多一个节点。
/**
* 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 p = new ListNode(-1);
ListNode head = p;
int ex = 0; //进位
//判断是否都遍历完 且最后没有进位
for (; l1 != null || l2 != null || ex != 0; ) {
//遍历完算作 0
int a = (l1 == null)?0 :l1.val;
int b = (l2 == null)?0 :l2.val;
int sum = a + b + ex;
//当前位数字
int val = sum % 10;
//生成新节点
ListNode q = new ListNode(val);
p.next = q;
p = q;
//更新进位
ex = sum / 10;
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
}
return head.next;
}
}
最终结果:
(感觉做的还行)
官方题解
个人思路与官方一样,只是官方把判断进位的代码放在外面了,直接在末尾生成了新节点
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;
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/add-two-numbers/solution/liang-shu-xiang-jia-by-leetcode/
来源:力扣(LeetCode)