66.两数相加
题目内容:
代码及思路:
1)原本自己的思路,有点繁琐,且当数字较大时容易溢出,被舍弃该种方法
#include<iostream>
#include<vector>
#include<stack>
#include<deque>
using namespace std;
struct ListNode
{
int val;
ListNode* next;
};
class Solution {
public:
ListNode* buildList()
{
ListNode* p1 = nullptr;
ListNode* p2 = nullptr;
ListNode* phead = nullptr;
int num;
char ch;
do
{
p1 = new ListNode();
cin >> num;
p1->val = num;
if (phead == nullptr)
{
phead = p1;
}
else
{
p2->next = p1;
}
p2 = p1;
cin.get(ch);
} while (ch == ',');
if (phead == nullptr)
return nullptr;
p2->next = nullptr;
return phead;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
stack<int> num1;
stack<int> num2;
ListNode* res = nullptr;
if (l1 == nullptr&&l2 != nullptr)
{
return l2;
}
if (l2 == nullptr&&l1 != nullptr)
{
return l1;
}
if (l1 == nullptr&&l2 == nullptr)
return nullptr;
while (l1 != nullptr)
{
num1.push(l1->val);
l1 = l1->next;
}
while (l2 != nullptr)
{
num2.push(l2->val);
l2 = l2->next;
}
int sum1 = 0, sum2 = 0;
while (!num1.empty())
{
sum1 = sum1 * 10 + num1.top();
num1.pop();
}
while (!num2.empty())
{
sum2 = sum2 * 10 + num2.top();
num2.pop();
}
int total = 0;
total = sum1 + sum2;
deque<int> result;
while (total > 0) //依次输出7,0,8
{
int num=total%10;
result.push_back(num);
total /= 10;
}
ListNode* head = nullptr;
ListNode* res_node = nullptr;
while (!result.empty())
{
res = new ListNode();
res->val = result.front();
if (head == nullptr)
head = res;
else
{
res_node->next = res;
}
res_node = res;
result.pop_front();
}
res_node->next = nullptr;
return head;
}
};
void main()
{
Solution* object = new Solution();
ListNode* l1 = new ListNode();
ListNode* l2 = new ListNode();
l1 = object->buildList();
l2 = object->buildList();
ListNode* res = new ListNode();
res = object->addTwoNumbers(l1, l2);
while (res != nullptr)
{
cout << res->val << endl;
res = res->next;
}
}
2)考虑进制的方式
逐位进行相加,设置进位项carry
/**
* 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)
{
ListNode* pNode=new ListNode(0);
ListNode* curr=pNode;
//进位
int carry=0;
while(l1||l2||carry) //要加上carry,保证当只有5和5时还有一个进位数
{
int num1=(l1)?(l1->val):0;
int num2=(l2)?(l2->val):0;
int sum=num1+num2+carry;
carry=sum/10;
//当前下一个结点
curr->next=new ListNode(sum%10);
curr=curr->next;
if(l1)
{
l1=l1->next;
}
if(l2)
{
l2=l2->next;
}
}
return pNode->next;
}
};