//Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
//Output: 7 -> 0 -> 8
//Explanation: 342 + 465 = 807.
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
int Link2Int(ListNode* pNode)
{
int Int_Num=0,add=1;
while(pNode)
{
Int_Num=Int_Num+pNode->val*add;
add=add*10;
pNode=pNode->next;
}
return Int_Num;
}
ListNode* Int2Link(int &Int_Num)
{
ListNode *pNode=new ListNode(-1);
pNode->next=NULL;
ListNode *ll=pNode;
ll->val=Int_Num%10;
Int_Num/=10;
while(Int_Num)
{
ListNode *pNode1=new ListNode(Int_Num%10);
pNode1->next=NULL;
ll->next=pNode1;
Int_Num/=10;
ll=ll->next;
}
return pNode;
}
//这个方法仅能支持短链表形式,大整数会溢出
ListNode* addTwoNumbers1(ListNode* l1, ListNode* l2)
{
if(l1==NULL) return l2;
if(l2==NULL) return l1;
int add_sum=Link2Int(l1) + Link2Int(l2);
return Int2Link(add_sum);
}
//这个方法可以表示大整数
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
ListNode* node1=l1;
ListNode* node2=l2;
int sum=0;
ListNode* pnode=new ListNode(0);
ListNode* node=pnode;
while(node1!=NULL||node2!=NULL)
{
sum/=10;
if(node1!=NULL)
{
sum+=node1->val;
node1=node1->next;
}
if(node2!=NULL)
{
sum+=node2->val;
node2=node2->next;
}
node->next=new ListNode(sum%10);
node=node->next;
}
if(sum/10==1)
node->next=new ListNode(1);
return pnode->next;
}
int main()
{
//ListNode* pNode1=new ListNode(2);
//ListNode* pNode2=new ListNode(4);
ListNode* pNode3=new ListNode(9);
//pNode1->next=pNode2;
//pNode2->next=pNode3;
pNode3->next=NULL;
ListNode* pNode4=new ListNode(1);
ListNode* pNode5=new ListNode(9);
ListNode* pNode6=new ListNode(9);
pNode4->next=pNode5;
pNode5->next=pNode6;
pNode6->next=NULL;
ListNode* pNode=addTwoNumbers(pNode3,pNode4);
while(pNode)
{
cout<<pNode->val;
if(pNode->next)
cout<<"->";
pNode=pNode->next;
}
cout<<endl;
return 0;
}
//g++ Add_Two_Numbers.cc -o Add_Two_Numbers
//./Add_Two_Numbers
3_Add Two Numbers
最新推荐文章于 2020-04-12 21:50:36 发布