题解作为笔记和回顾学习使用,请大佬们多多指教
整数相加(链表)
力扣第二题
难度:中等
两个非空列表逆序存储整数,计算结果并以相同的方式返回一个结果链表
这道题的主要思路是两个链表的同一位置的结点的值相加得到结果和一个进位值,进位值和两个链表的下一个位置的结点的值相加再得到新的值,以此类推。
让我们设两个链表的每一个位置的结点的值为n1,n2,进位值为carry,则
答案链表处相应位置的数字为 (n1+n2+carry) mod 10,而新的进位值为 (n1+n2+carry)/10
接下来看一下代码的实现
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null, tail = null;
int carry = 0;
while (l1 != null || l2 != null) {
int n1 = l1 != null ? l1.val : 0;
int n2 = l2 != null ? l2.val : 0;
int sum = n1 + n2 + carry;
if (head == null) {
head = tail = new ListNode(sum % 10);
} else {
tail.next = new ListNode(sum % 10);
tail = tail.next;
}
carry = sum / 10;
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
}
if (carry > 0) {
tail.next = new ListNode(carry);
}
return head;
}
}
就是暴力遍历链表然后逐个相加得出结果。