LeetCode 445. Add Two Numbers II
题目描述:
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
输入的两个链表是不允许反转的,如果可以翻转,那就和第2号问题一样了。
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
思路分析
我才用了栈来作为辅助的数据结构,其实实现的也是反转(利用栈的性质存储);再由一个链表进行存储加和;最后将这个存储的链表进行反转即可。
具体代码:
/**
* 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) {
if(l1==NULL&&l2==NULL)
return NULL;
//用栈反转两个加数
stack<ListNode*>s1,s2;
while(l1||l2)
{
if(l1)
{
s1.push(l1);
l1=l1->next;
}
if(l2)
{
s2.push(l2);
l2=l2->next;
}
}
//相加存入一个新链表
ListNode* dumy=new ListNode(0);
ListNode*p=dumy;
int flag=0;
while((!s1.empty())||(!s2.empty())||flag)
{
int t1,t2;
if(!s1.empty())
{
t1=s1.top()->val;
s1.pop();
}
else
t1=0;
if(!s2.empty())
{
t2=s2.top()->val;
s2.pop();
}
else
t2=0;
int sum=t1 + t2+ flag;
flag=sum/10;
p->next=new ListNode(sum%10);
p=p->next;
}
//反转链表
ListNode* pre=NULL;
ListNode* cur=dumy->next;
while(cur)
{
ListNode* last=cur->next;
cur->next=pre;
pre=cur;
cur=last;
}
return pre;
}
};