2. 两数相加
https://leetcode-cn.com/problems/add-two-numbers/
解法一:
就如同竖式加法,只是倒过来
遍历两个链表,对应位相加,进位向后传递。难点:链表长度不同时处理,以及进位处理.
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* head = new ListNode(0); //头结点
ListNode* tmp = head; //工作节点
int upgrade = 0; //进位标志
while (l1 || l2 || upgrade) {
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + upgrade;
upgrade = sum / 10;
tmp->next = new ListNode(sum % 10);
l1 = l1 ? l1->next : NULL; //判断是否有后继
l2 = l2 ? l2->next : NULL;
tmp = tmp->next;
}
return head->next; //头结点不使用
}
};
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(0)
work = head
upgrade = 0
while l1 or l2 or upgrade:
sum = (l1.val if l1 else 0) + (l2.val if l2 else 0) + upgrade
upgrade = sum // 10 #进位
sum %= 10
work.next = ListNode(sum)
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
work = work.next
return head.next
最后更新于