概述
2. 两数相加
445. 两数相加 II
2. 两数相加
这道题头疼的地方就是链表长度不一样
我们处理一下链表,让l1的长度始终大于等于l2,然后只对这种情况处理,逻辑就会好写很多
遍历两趟
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
# 先把链表处理成l1最长
p1,p2 = l1,l2
while p1.next and p2.next:
p1=p1.next
p2=p2.next
# 相同长度不影响,p2比p1长时会把l2接到l1上
if not p1.next:
p1.next = p2.next
p2.next = None
p1,p2 = l1,l2
tail = p1
res = 0
while p1 and p2:
p1.val += p2.val + res
res = 0
if p1.val>9:
res = 1
p1.val -= 10
tail = p1
p1 = p1.next
p2 = p2.next
# 处理剩余情况
while p1:
p1.val += res
res = 0
if p1.val>9:
res = 1
p1.val -= 10
if not res:
return l1
tail = p1
p1 = p1.next
# 还有进位
if res:
tail.next = ListNode(res)
return l1
不使用新的链表,缺点是要额外遍历一趟链表
使用新链表
我们也可以用新的链表,然后一趟遍历就行,具体怎么实现看要求
c++代码
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *head = nullptr, *tail = nullptr;
int carry = 0;
while (l1 || l2) {
int n1 = l1 ? l1->val: 0;
int n2 = l2 ? l2->val: 0;
int sum = n1 + n2 + carry;
if (!head) {
head = tail = new ListNode(sum % 10);
} else {
tail->next = new ListNode(sum % 10);
tail = tail->next;
}
carry = sum / 10;
if (l1) {
l1 = l1->next;
}
if (l2) {
l2 = l2->next;
}
}
if (carry > 0) {
tail->next = new ListNode(carry);
}
return head;
}
};
445. 两数相加 II
和上一道题不同的是,这里链表存储的是高位,用暴力依然好写
暴力
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
def read_number(head):
n = 0
while head:
n = head.val + n*10
head = head.next
return n
a,b = read_number(l1),read_number(l2)
c = a+b
ans = ListNode(-1)
node = ListNode(c%10,ans.next)
ans.next = node
c//=10
while c:
node = ListNode(c%10,ans.next)
ans.next = node
c//=10
return ans.next
用栈
标准题解是用栈,没什么特殊的技巧,直接贴答案了
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
s1, s2 = [], []
while l1:
s1.append(l1.val)
l1 = l1.next
while l2:
s2.append(l2.val)
l2 = l2.next
ans = None
carry = 0
while s1 or s2 or carry != 0:
a = 0 if not s1 else s1.pop()
b = 0 if not s2 else s2.pop()
cur = a + b + carry
carry = cur // 10
cur %= 10
curnode = ListNode(cur)
curnode.next = ans
ans = curnode
return ans
不得不感慨题解写的代码精简很多,而且这个代码是从后往前构造链表的,注意看curnode和ans那两行代码