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 = nullptr, *tail = nullptr;//新建链表,头尾指针
int carry = 0;//进位
while (l1 || l2)
{
int n1 = l1 ? l1->val: 0;//l1在某一位的值
int n2 = l2 ? l2->val: 0;//l2在相应位的值
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、l2的下一位(没有就不变,没有的话“->next”就不存在)
if (l1)
{
l1 = l1->next;
}
if (l2)
{
l2 = l2->next;
}
}
//循环结束,判断是否最高位有进位
if (carry > 0)
{
tail->next = new ListNode(carry);
}
return head;
}
};
记录原先的想法:没有开个新的链表,而是把答案添加到l1里去,就,好多要判断啊。。。看了下,也没考虑全。。。
!!!新建链表设俩指针
时隔五天重做
/**
* 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) {
int carry=0,sum=0,x=0,y=0;
ListNode* head=nullptr,*tail=nullptr;
while(l1||l2)
{
x=l1?l1->val:0;
y=l2?l2->val:0;
sum=x+y+carry;
carry=sum/10;
if(head==nullptr)
{
head=new ListNode(sum%10);
tail=head;
}
else
{
tail->next=new ListNode(sum%10);
tail=tail->next;
}
if(l1)
{
l1=l1->next;
}
if(l2)
{
l2=l2->next;
}
}
while(carry>0)//其实直接用if就好,因为进位只会是一个个位数
{
tail->next=new ListNode(carry%10);
tail=tail->next;
carry=carry/10;
}
return head;
}
};
有遇到过一个错误:
AddressSanitizer:DEADLYSIGNAL
=================================================================
==42==ERROR: AddressSanitizer: SEGV on unknown address (pc 0x00000037afec bp 0x7fff45df1c30 sp 0x7fff45df1ae0 T0)
==42==The signal is caused by a READ memory access.
==42==Hint: this fault was caused by a dereference of a high value address (see register values below). Dissassemble the provided pc to learn which register was used.
#4 0x7f416a2ba0b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
AddressSanitizer can not provide additional info.
==42==ABORTING
找到的错误原因是没有给两个指针初始化(如下)
//错误
ListNode* head,*tail;
//修改后
ListNode* head=nullptr,*tail=nullptr;