-
Notifications
You must be signed in to change notification settings - Fork 0
/
2.两数相加.cpp
45 lines (41 loc) · 1.01 KB
/
2.两数相加.cpp
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
* @lc app=leetcode.cn id=2 lang=cpp
*
* [2] 两数相加
*/
// @lc code=start
/**
* 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 * p = new ListNode;
ListNode * tail = p;
int flag = 0;
while (l1 || l2 )
{
int val1 = l1?l1->val:0;
int val2 = l2?l2->val:0;
//创建新节点
ListNode * n = new ListNode;
n->val = (val1 + val2 + flag)%10;
flag = (val1 + val2 + flag)/10; //标志进位符
//添加新节点
tail->next = n;
tail = n;
//结点后移
l1 = l1?l1->next:l1;
l2 = l2?l2->next:l2;
}
//任然有进位
if(flag == 1) tail->next = new ListNode(1);
return p->next;
}
};
// @lc code=end