Problem: 2. 两数相加
文章目录
题目描述
思路
1.创建虚拟头节点dummy,用于存储相加的结果数字;
2.让指针p1、p2、tail分别指向l1、l2、dummy,定义int变量carry记录每次相加的进位值;
3.当p1不为空或者p2不为空时,定义int变量sum:
3.1 若p1不为空:sum += p1 -> val ;
3.2 若p2不为空:sum += p2 -> val ;
3.3 若craay不为空: sum += carry ;
3.4 生成当前的结果(tail -> next = new ListNode(sum % 10); ),并更新carry(carry = sum / 10; )
3.5 最后遍历完l1与l2后carry还不为0,则再将其添加到结果链表末尾
复杂度
时间复杂度:
O ( m a x ( m , n ) ) O(max(m,n)) O(max(m,n));其中 m m m为链表l1的长度, n n n为链表l2的长度
空间复杂度:
O ( m + n ) O(m + n) O(m+n)
Code
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
/**
*
* @param l1 Given linked list l1
* @param l2 Given linked list l2
* @return ListNode*
*/
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* p1 = l1;
ListNode* p2 = l2;
int carry = 0;
ListNode* dummy = new ListNode(666);
ListNode* tail = dummy;
if (l1 == nullptr) {
return l2;
}
if (l2 == nullptr) {
return l1;
}
while (p1 != nullptr || p2 != nullptr) {
int sum = 0;
if (p1 != nullptr) {
sum += p1 -> val;
p1 = p1 -> next;
}
if (p2 != nullptr) {
sum += p2 -> val;
p2 = p2 -> next;
}
if (carry != 0) {
sum += carry;
}
tail -> next = new ListNode(sum % 10);
carry = sum / 10;
tail = tail -> next;
}
//If carry is not equal to 0
if (carry != 0) {
tail -> next = new ListNode(carry);
}
return dummy -> next;
}
};