# 力扣第二题:两数相加

2021/8/21 18:37:55 浏览：

``````#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
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) {}
};
{
int temp = 0;//用于计算新节点in的value
int flag = 0;//用于进位
int judge = 1;//只用一次用来判断是不是第一次
while (!(l1==nullptr&&l2==nullptr))
{
if(judge!=1)
{  //第一次不用new
ListNode* in = new ListNode();
p->next = in;
p = p->next;
}
judge = 0;
if (l1==nullptr) //l1为空则l2肯定不为空(否则进不来循环)
{
temp=l2->val + flag;   //temp只需计算flag和l2->val
l2 = l2->next;
}
else//l1不为空,l2可能为空,也可能不为空
{
if (l2 == nullptr)
{  //l1不空,l2空
temp = l1->val + flag;  //temp只需计算flag和l1->value
}
else   //l1,l2都不为空
{
temp = l1->val +l2->val+ flag;
l2 = l2->next;
}
l1 = l1->next;
}
p->val=temp % 10; //temp>10则需对10求模

//计算进位
if (temp >= 10)
flag = 1;
else
flag = 0;
}

//考虑到最后的进位 需不需要多一个节点
if (flag == 1) {
ListNode* in = new ListNode(1);
p->next = in;
p = in;
}
}
int main()
{
ListNode* l1 = new ListNode();
ListNode* p1 = l1;
ListNode* l2 = new ListNode();
ListNode* p2 = l2;
cout << "请输入l1的个数:";
int num,i;
cin >> num;
for (i = 0; i < num; i++) {
cout << "请输入l1的第"<<i+1<<"个数据:";
cin >> p1->val;
if(i!=num-1)
{
ListNode* in = new ListNode();
p1->next = in;
p1 = in;
}

}
cout << "请输入l2的个数:";
cin >> num;
for (i = 0; i < num; i++) {
cout << "请输入l2的第" << i + 1 << "个数据:";
cin >> p2->val;
if (i != num - 1)
{
ListNode* in = new ListNode();
p2->next = in;
p2 = in;
}

}
cout << endl << "结果:" << endl;
while (ret) {
cout << ret->val << endl;
ret = ret->next;
}
cout << "=========================" << endl;
cout << "链表1:" << endl;
while (l1) {
cout << l1->val << endl;
l1 = l1->next;
}
cout << "=========================" << endl;
cout << "链表2:" << endl;
while (l2) {
cout << l2->val << endl;
l2 = l2->next;
}
return 0;
}
``````