/**
* 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)
{
int len1 = 1; int len2 = 1;
//让p1和p2代替头结点进行遍历
ListNode* p1 = l1; ListNode* p2 = l2;
//找出l1和l2的尾结点,记录l1和l2的长度
while (p1->next != NULL)
{
p1 = p1->next;
len1++;
}
while (p2->next != NULL)
{
p2 = p2->next;
len2++;
}
//进行补0操作
//假设len1比len2长
if (len1 > len2)
{
for (int i = 1; i <= len1 - len2; i++)
{
p2->next = new ListNode(0);
p2 = p2->next;
}
}
//len2比len1长
else
{
for (int i = 1; i <= len2 - len1; i++)
{
p1->next = new ListNode(0);
p1 = p1->next;
}
}
//进行相加操作
p1=l1;
p2=l2;
int temp = 0;
bool count=false;
ListNode* l3=new ListNode(-1);//用于函数返回值的链表l3
ListNode* w = l3;//代替l3的指针w
int maxnum = len1 > len2 ? len1 : len2;
for (int i = 1; i <= maxnum; i++)
{
temp = count + p1->val + p2->val;
w->next = new ListNode(temp%10);//创建相加以后的链表
count = temp >= 10 ? true : false;
w = w->next;
p1 = p1->next;
p2 = p2->next;
}
//如果最后两个数相加还有进位,则再创建一个节点来存放
if (count)
{
w->next = new ListNode(1);
w = w->next;
}
return l3->next;
}
};