https://leetcode-cn.com/problems/add-two-numbers/submissions/
今天刷的是第二题,当初因为没学链表,一直没刷。这个暑假,把数据结构稍微学了下,再回头看这题。刚开始看的时候,还是感觉有些生疏,毕竟数据结构是暑假自学的,不太牢固。
下面是力扣的官方题解。我在官方题解上面加了注释!!
/**
* 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 = nullptr, *tail = nullptr;
//carry表示进位
int carry = 0;
//只要l1或者l2不为空就进行相加
while (l1 || l2) {
//如果出现链表的一端已经没有数了,而另一端还有数。比如123+56;循环第三次时n1=1;n2=0;
int n1 = l1 ? l1->val: 0;
int n2 = l2 ? l2->val: 0;
int sum = n1 + n2 + carry;
//头结点为空
if (!head) {
head = tail = new ListNode(sum % 10);
}
//头结点不为空,不断向后扩展结点
else {
tail->next = new ListNode(sum % 10);
tail = tail->next;
}
//下一次进位的数
carry = sum / 10;
//l1不为空,l1指向下一次的指针
if (l1) {
l1 = l1->next;
}
//l2不为空,L2指向下一次的指针
if (l2) {
l2 = l2->next;
}
}
//和数比两个加数多出了1位;比如100+900=1000;
//此时carry就是1;
if (carry > 0) {
tail->next = new ListNode(carry);
}
//返回头指针
return head;
}
};
我接着自己又写了一遍代码。(用自己的方法,时间和空间复杂度比官方解答更好哦)不过刚写的时候,出了点错误。我到淘宝上买了个力扣会员,用他们的调试器调试了一下,把错误改正了。下面是我的代码。
/**
* 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=nullptr;ListNode*tail=nullptr;
head=new ListNode((l1->val+l2->val)%10);
tail=head;
int carry=(l1->val+l2->val)/10;
l1=l1->next;l2=l2->next;
while(l1||l2){
int n1=l1?l1->val:0;
int n2=l2?l2->val:0;
int sum=n1+n2+carry;
tail->next=new ListNode(sum%10);
tail=tail->next;
carry=sum/10;
if(l1)l1=l1->next;
if(l2)l2=l2->next;
}
if(carry){tail->next=new ListNode(carry);
tail=tail->next;
}
return head;
}
};
我第一次写犯的错误
第二次就好了哦
已知乾坤大,犹怜草木青。这里北风,星河辽阔,一路相伴。