#include <stdio.h>
/**
* 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) {}
* };
*/
struct ListNode {
int val;
struct ListNode *next;
};
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
ListNode* l3 = new ListNode;
ListNode* l4 = l3;
int temp1=0;
int multi =1;
int temp2 = 0;
int multi2 = 1;
//定位到最右边
while (l1!=NULL)
{
temp1 += (l1->val)*multi;
l1 = l1->next;
multi = multi*10;
}
while (l2!=NULL)
{
temp2 += (l2->val)*multi2;
l2 = l2->next;
multi2 = multi2*10;
}
int temp3 = temp1+temp2;
//提取L3的每一位数字并插入链表
//ListNode* p1 = new ListNode;
if(temp3<10)
{
l3->val = temp3%10;
l3->next = NULL;
temp3 = temp3/10;
return l4;
}
l3->val = temp3%10;
l3->next = NULL;
temp3 = temp3/10;
while (temp3>=10)
{
int t = temp3%10;
//尾插法
ListNode* cur = new ListNode;
cur->val = t;
cur->next = NULL;
l3->next = cur;
l3 = cur;
temp3 = temp3/10;
}
int t = temp3%10;
//尾插法
ListNode* cur = new ListNode;
cur->val = t;
cur->next = NULL;
l3->next = cur;
return l4;
}
int main(void)
{
ListNode* l1 = new ListNode;
l1->val =1;
l1->next=NULL;
ListNode* l11 = new ListNode;
l11->val =1;
l11->next = 0;
ListNode* p = addTwoNumbers(l1,l11);
while (p!=NULL)
{
printf("%d\n",p->val);
p=p->next;
}
return 0;
}
如何解决?