Leetcode445 两数相加||(单链表)_栈

 

两数相加模板:

//n进制数相加

int carry=0;
int bit;
int 数1,数2;
point1指向数1的最低位,point2指向数2的最低位
res;//结果
while(point1不到最高位&&point2不到最高位)
{
     bit=point1->val +point2->val+carry;
     if(bit>=n)
     {
         carry=1;
        结果最后加入数(bit-n);
       
 
     }
     else
     {
         carry=0;
         结果最后加入数(bit);
     }
}
while(point1不到最高位)
{
    bit= point1->val+carry;
    if(bit>=n)
    {
        carry=1;
       结果加入数(bit-n);
        
    }
    else{
        carry=0;
        结果加入数(bit);
    }
}
while(point2不到最高位)
{
    bit=point2->val+carry;
    if(bit>=n)
    {
        carry=1;
        结果加入数(bit-10);
    }
    else{
        carry=0;
        结果加入数(bit);
    
    }
}
//如果到最后还有进位没加
if(carry==1)
{
    结果加入数(1);
}
return 结果;
    }
};

具体思路:

(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) {
stack<ListNode*>st1;
stack<ListNode*>st2;
ListNode *head=new ListNode();
ListNode *p=l1;
while(p)
{
    st1.push(p);
    p=p->next;
}
p=l2;
while(p)
{
    st2.push(p);
    p=p->next;
}
ListNode *p1,*p2,*s;
int carry=0;
int bit;
while(!st1.empty()&&!st2.empty())
{
    p1=st1.top();
     st1.pop();
     p2=st2.top();
     st2.pop();
     bit=p1->val+p2->val+carry;
     if(bit>=10)
     {
         carry=1;
        s=new ListNode(bit-10);
        s->next=head->next;
        head->next=s;
     }
     else
     {
         carry=0;
         s=new ListNode(bit);
         s->next=head->next;
         head->next=s;
     }
}
while(!st1.empty())
{
    p1=st1.top();
    st1.pop();
    bit=p1->val+carry;
    if(bit>=10)
    {
        carry=1;
        s=new ListNode(bit-10);
        s->next=head->next;
        head->next=s;
    }
    else{
        carry=0;
        s=new ListNode(bit);
        s->next=head->next;
        head->next=s;
    }
}
while(!st2.empty())
{
    p2=st2.top();
    st2.pop();
    bit=p2->val+carry;
    if(bit>=10)
    {
        carry=1;
        s=new ListNode(bit-10);
        s->next=head->next;
        head->next=s;
    }
    else{
        carry=0;
        s=new ListNode(bit);
        s->next=head->next;
        head->next=s;
    }
}
if(carry==1)
{
    s=new ListNode(1);
    s->next=head->next;
    head->next=s;
}
return head->next;
    }
};