两数相加
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
思路:
双指针,大体流程:
- 利用两指针分别指向两个链表
- cycle1:记录两指针值的和sum,将sum%10连接到新链表中;若sum有余值remain(sum/10==1),将remain保留到下个节点中,直到有链表遍历完
- cycle2:遍历剩余的链表,与cycle1过程类似
- 注意可能的remain:两个链表遍历完后还有remain,创建节点连接到新链表中
代码:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if (!l1)
return l2;
if (!l2)
return l1;
ListNode *p1 = l1, *p2 = l2;
ListNode *head = nullptr, *tmp = nullptr;
int remain = 0, sum = 0;
while (p1 && p2) {
sum = remain + p1->val + p2->val;
remain = sum / 10;
if (!head) {
head = new ListNode(sum % 10);
tmp = head;
} else {
tmp->next = new ListNode(sum % 10);
tmp = tmp->next;
}
p1 = p1->next;
p2 = p2->next;
}
while (p1) {
sum = remain + p1->val;
remain = sum / 10;
tmp->next = new ListNode(sum % 10);
tmp=tmp->next;
p1 = p1->next;
}
while (p2) {
sum = remain + p2->val;
remain = sum / 10;
tmp->next = new ListNode(sum % 10);
tmp=tmp->next;
p2 = p2->next;
}
if(remain){
tmp->next = new ListNode(1);
}
return head;
}
};