mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2026-06-27 10:09:11 +00:00
Create 2. Add Two Numbers.md
This commit is contained in:
parent
e3033f814d
commit
57102d2044
44
2. Add Two Numbers.md
Normal file
44
2. Add Two Numbers.md
Normal file
@ -0,0 +1,44 @@
|
||||
# [2. Add Two Numbers](https://leetcode.com/problems/add-two-numbers/)
|
||||
# 思路
|
||||
从前到尾不断将两个链表的元素相加就行了,这个过程中一直会用到一个代表进位的变量cin,另外注意处理两个链表不等长的情况。
|
||||
|
||||
# C++
|
||||
``` C++
|
||||
class Solution {
|
||||
private:
|
||||
int digit_add(const int a, const int b, int& cin){ // 先定义一个一位数字相加的函数,方便后面使用,注意是用引用的方式传入cin的
|
||||
int sum = a + b + cin;
|
||||
cin = sum / 10;
|
||||
return sum % 10;
|
||||
}
|
||||
public:
|
||||
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
|
||||
int cin = 0; // 进位
|
||||
ListNode *root = new ListNode(digit_add(l1 -> val, l2 -> val, cin)); // root是最后要返回的指针
|
||||
ListNode *last = root; // last指向当前结果链表中的最后一个元素
|
||||
l1 = l1 -> next;
|
||||
l2 = l2 -> next;
|
||||
while(l1 && l2){ // 由前先后对两个链表的元素相加
|
||||
last -> next = new ListNode(digit_add(l1 -> val, l2 -> val, cin));
|
||||
last = last -> next;
|
||||
l1 = l1 -> next;
|
||||
l2 = l2 -> next;
|
||||
}
|
||||
if(l2) l1 = l2; // 若l2长一些,将l1指向l2,后续就只对l1处理就行了.
|
||||
while(l1 && cin > 0){
|
||||
last -> next = new ListNode(digit_add(l1 -> val, 0, cin));
|
||||
last = last -> next;
|
||||
l1 = l1 -> next;
|
||||
}
|
||||
if(l1) last -> next = l1; // cin = 0,直接将l1后续的所有节点接到last后面就行了
|
||||
else{ // l1 == NULL, cin >= 0
|
||||
if(cin > 0){
|
||||
last -> next = new ListNode(cin);
|
||||
last = last -> next;
|
||||
}
|
||||
last -> next = NULL;
|
||||
}
|
||||
return root;
|
||||
}
|
||||
};
|
||||
```
|
||||
Loading…
Reference in New Issue
Block a user