
我的思路
这个题目感觉非常不优雅,代码写的太多了,不过题目难度倒是不难,本质上就是先将两个链表翻转,然后逐个进行相加运算即可,重点在于需要定义一个尾指针,方便一个讲长的那个拼接到短的上。
同时还需要注意如果两个链表等长,但是有进位,需要用尾指针进行新建节点,而不能用遍历的时候节点。
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head1 = reverse(l1);
ListNode head2 = reverse(l2);
int a = 0,sum=0;
ListNode pre1 = head1;
ListNode pre2 = head2;
ListNode tail = head1;
while(pre1!=null&&pre2!=null){
a = pre1.val+pre2.val+sum;
sum =0;
if(a>=10){
a=a-10;
sum=1;
}
pre1.val = a;
tail = pre1;
pre1 = pre1.next;
pre2 = pre2.next;
}
if(pre2!=null){
tail.next = pre2;
pre1 = pre2;
}
while(sum==1){
if(pre1!=null){
a= pre1.val+sum;
sum=0;
if(a>=10){
a=a-10;
sum=1;
}
pre1.val = a;
tail = tail.next;
pre1 = pre1.next;
}
else{
tail.next = new ListNode(1,null);
break;
}
}
return reverse(head1);
}
public ListNode reverse(ListNode head){
ListNode temp = head;
ListNode pre = null;
while(head!=null){
temp = head.next;
head.next = pre;
pre = head;
head = temp;
}
return pre;
}
}
灵神的思路
灵神是用递归来做的,不断调用这个addTwo方法。感觉 没有我的好明白。不过灵神的代码写的真优雅啊,我的代码就是一坨了,丑陋不堪。
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
l1 = reverseList(l1);
l2 = reverseList(l2); // l1 和 l2 反转后,就变成【2. 两数相加】了
ListNode l3 = addTwo(l1, l2, 0);
return reverseList(l3);
}
private ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head; // 把下一个节点指向自己
head.next = null; // 断开指向下一个节点的连接,保证最终链表的末尾节点的 next 是空节点
return newHead;
}
// l1 和 l2 为当前遍历的节点,carry 为进位
private ListNode addTwo(ListNode l1, ListNode l2, int carry) {
if (l1 == null && l2 == null) { // 递归边界:l1 和 l2 都是空节点
return carry != 0 ? new ListNode(carry) : null; // 如果进位了,就额外创建一个节点
}
if (l1 == null) { // 如果 l1 是空的,那么此时 l2 一定不是空节点
l1 = l2;
l2 = null; // 交换 l1 与 l2,保证 l1 非空,从而简化代码
}
carry += l1.val + (l2 != null ? l2.val : 0); // 节点值和进位加在一起
l1.val = carry % 10; // 每个节点保存一个数位
l1.next = addTwo(l1.next, (l2 != null ? l2.next : null), carry / 10); // 进位
return l1;
}
}
作者:灵茶山艾府
链接:https://leetcode.cn/problems/add-two-numbers-ii/solutions/2328330/fan-zhuan-lian-biao-liang-shu-xiang-jia-okw6q/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
861

被折叠的 条评论
为什么被折叠?



