forked from illuz/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAC_simulation_n.cpp
73 lines (65 loc) · 1.59 KB
/
AC_simulation_n.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* Author: illuz <iilluzen[at]gmail.com>
* File: AC_simulation_n.cpp
* Create Date: 2014-11-28 08:36:27
* Descripton:
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 0;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *addValAndCreateNewNode(ListNode *cur, int val) {
cur->val = val;
cur->next = new ListNode(0);
return cur->next;
}
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode *ret = new ListNode(0);
ListNode *cur = ret;
int sum = 0;
while (1) {
if (l1 != NULL) {
sum += l1->val;
l1 = l1->next;
}
if (l2 != NULL) {
sum += l2->val;
l2 = l2->next;
}
cur->val = sum % 10;
sum /= 10;
if (l1 != NULL || l2 != NULL || sum)
cur = (cur->next = new ListNode(0));
else
break;
}
return ret;
}
};
int main() {
int t, n;
Solution s;
while (cin >> n) {
ListNode *a = new ListNode(0), *b = new ListNode(0);
ListNode *pa = a, *pb = b;
while (n--) {
cin >> t;
pa = addValAndCreateNewNode(pa, t);
}
cin >> n;
while (n--) {
cin >> t;
pb = addValAndCreateNewNode(pb, t);
}
s.addTwoNumbers(a, b); // use gdb to debug
// a & b will not release!
}
return 0;
}