题目:2. Add Two Numbers
类型:链表
难度:中等
星级:五星推荐
题意:类似于模拟大数相加,注意进位,同时题目给了很多友好的部分。首先链表是逆序的,所以模拟加法可以直接相加。其次输出也不要求反转链表。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* head = new ListNode(-1);
ListNode* cur = head;
int sum=0;
int c=0;
while(l1||l2){
sum=0;
if(l1){
sum+=l1->val;
l1=l1->next;
}
if(l2){
sum+=l2->val;
l2=l2->next;
}
cur->next = new ListNode((sum+c)%10);
c=(sum+c)/10;
cur=cur->next;
}
if(c){
cur->next=new ListNode(1);
}
return head->next;
}
};
版本2
2020.3.39
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
//先计算出来 然后再反转链表吗
int c = 0;
ListNode* dummy = new ListNode(-1);
ListNode* cur = dummy;
while(l1 || l2){
int a = l1? l1->val: 0;
int b = l2? l2->val: 0;
c += a+b;
cur->next = new ListNode(c%10);
c /= 10;
cur = cur->next;
if(l1) l1 = l1->next;
if(l2) l2 = l2->next;
}
if(c) cur->next = new ListNode(1), cur = cur->next;
return dummy->next;
}
};

本文详细解析了LeetCode上的一道经典链表题目——两数相加。通过两个逆序链表模拟大数相加的过程,重点介绍了如何处理进位问题,并提供了两种不同的解决方案,一种直接返回结果链表,另一种则在计算完成后进行链表反转。

1090

被折叠的 条评论
为什么被折叠?



