原方法:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
auto l3 = new ListNode(-1);
auto res = l3;
int jinwei = 0;
while(l1 && l2)
{
l3->val = l1->val + l2->val + jinwei;
if(l3->val > 9)
{
l3->val = l3->val - 10;
jinwei = 1;
}
else jinwei = 0;
l1 = l1->next;
l2 = l2->next;
if(l1 && l2)
{
l3->next = new ListNode(-1);
l3 = l3->next;
}
}
while(l1)
{
l3->next = new ListNode(-1);
l3 = l3->next;
l3->val = l1->val + jinwei;
jinwei = 0;
if(l3->val > 9)
{
l3->val -= 10;
jinwei = 1;
}
l1 = l1->next;
}
while(l2)
{
l3->next = new ListNode(-1);
l3 = l3->next;
l3->val = l2->val + jinwei;
jinwei = 0;
if(l3->val > 9)
{
l3->val -= 10;
jinwei = 1;
}
l2 = l2->next;
}
while(jinwei)
{
l3 -> next = new ListNode(1);
jinwei = 0;
}
return res;
}
};
末尾补0:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
auto temp1 = l1;
auto temp2 = l2;
int cnt1 = 0;
int cnt2 = 0;
while(temp1->next)
{
temp1 = temp1->next;
cnt1++;
}
while(temp2->next)
{
temp2 = temp2->next;
cnt2++;
}
int diff = cnt1 - cnt2;
while(diff > 0)
{
temp2->next = new ListNode(0);
temp2 = temp2->next;
diff--;
}
while(diff < 0)
{
temp1->next = new ListNode(0);
temp1 = temp1->next;
diff++;
}
auto l3 = new ListNode(-1);
auto res = l3;
int jinwei = 0;
while(l1 && l2)
{
l3->val = l1->val + l2->val + jinwei;
if(l3->val > 9)
{
jinwei = 1;
l3 ->val -= 10;
}
else jinwei = 0;
l1= l1->next;
l2= l2->next;
if(l1 && l2)
{
l3->next = new ListNode(-1);
l3 = l3 ->next;
}
}
if(jinwei)
{
l3->next = new ListNode(1);
}
return res;
}
};
这种方法修改了原题中给出的两个链表,由于记录了链表初始长度,可以考虑后续删掉新增加的0;
//复原节点(未删除空间)
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
auto temp1 = l1;
auto temp2 = l2;
auto temp3 = l1;
auto temp4 = l2;
int cnt1 = 0;
int cnt2 = 0;
while(temp1->next)
{
temp1 = temp1->next;
cnt1++;
}
while(temp2->next)
{
temp2 = temp2->next;
cnt2++;
}
int diff = cnt1 - cnt2;
while(diff > 0)
{
temp2->next = new ListNode(0);
temp2 = temp2->next;
diff--;
}
while(diff < 0)
{
temp1->next = new ListNode(0);
temp1 = temp1->next;
diff++;
}
auto l3 = new ListNode(-1);
auto res = l3;
int jinwei = 0;
while(l1 && l2)
{
l3->val = l1->val + l2->val + jinwei;
if(l3->val > 9)
{
jinwei = 1;
l3 ->val -= 10;
}
else jinwei = 0;
l1= l1->next;
l2= l2->next;
if(l1 && l2)
{
l3->next = new ListNode(-1);
l3 = l3 ->next;
}
}
if(jinwei)
{
l3->next = new ListNode(1);
}
int cnt3 = 0;
if(cnt2 < cnt1)
{
while(cnt3 < cnt2)
{
temp4= temp4->next;
cnt3++;
}
temp4->next = NULL;
}
if(cnt2 > cnt1)
{
while(cnt3 < cnt1)
{
temp3= temp3->next;
cnt3++;
}
temp3->next = NULL;
}
return res;
}
};