LeetCode-Add Two Numbers

题目

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public:
ListNode* (ListNode* l1, ListNode* l2) {
ListNode *p = l1, *q = l2;
ListNode *listNode = new ListNode(0);
ListNode *T = listNode;
int carry = 0;

while (p!=NULL||q!=NULL)
{
if(p!=NULL)
{
carry = carry + p -> val;
p = p -> next;
}
if(q!=NULL)
{
carry = carry + q -> val;
q = q -> next;
}
T -> next = new ListNode ( carry % 10 );
T = T -> next;
carry = carry / 10;

}

if(carry==1)
p3 -> next = new ListNode(1);
return listNode->next;
}