题目链接:
https://leetcode-cn.com/problems/add-two-numbers/
代码:
/**
- 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 *p1 = l1;
ListNode *p2 = l2;
ListNode *head = new ListNode(0) ;
ListNode *phead = head;
int num = 0;
if(p1 ==NULL&& p2 == NULL)
return head;
while(num!=0||p1!=NULL||p2!=NULL)
{
int num1,num2;
num1 = num2 = 0;
if(p1!=NULL)
{
num1 = p1->val;
}
if(p2!=NULL)
{
num2 = p2->val;
}
int result = num1 + num2 + num;
int val = result%10;
num = result/10;
ListNode *r = new ListNode(0);
r->next = NULL;
r->val = val;
phead->next= r;
phead=phead->next;
if(p1!=NULL)
{
p1=p1->next;
}
if(p2!=NULL)
{
p2=p2->next;
}
}
phead = head->next;
delete head;
return phead;
}
};