2.两数相加(中等)
https://leetcode-cn.com/problems/add-two-numbers/
个人理解:
(1)两个链表有先结束和后结束。(2)相加是有进位的如果两个链表最后两数相加有进位,则需要把这个进位的值考虑进去,需要在循环判断的时候考虑这一点。
/**
* 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:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* head = new ListNode(-1);
ListNode* p = head; //遍历指针
int sum = 0;
int temp = 0;
int carryDight = 0;
while (l1!=NULL || l2!=NULL || carryDight){
// temp = 0;
if (l1 != NULL){
sum += l1->val;
l1 = l1->next;
}
if (l2 != NULL){
sum += l2->val;
l2 = l2->next;
}
if (sum >= 10){
temp = sum % 10;
sum = 1;
carryDight = 1;
} else{
temp = sum;
sum = 0;
carryDight = 0;
}
ListNode* newlocation = new ListNode(temp);
p->next = newlocation;
p = p->next;
}
// 删除head节点
p = head->next; //让遍历指针再次执行第一个节点。
delete head;
return p;
}
};