-
Notifications
You must be signed in to change notification settings - Fork 643
/
2.4.cpp
92 lines (86 loc) · 1.63 KB
/
2.4.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <iostream>
using namespace std;
typedef struct node{
int data;
node *next;
}node;
node* init(int a[], int n){
node *head=NULL, *p;
for(int i=0; i<n; ++i){
node *nd = new node();
nd->data = a[i];
if(i==0){
head = p = nd;
continue;
}
p->next = nd;
p = nd;
}
return head;
}
node* addlink(node *p, node *q){
if(p==NULL) return q;
if(q==NULL) return p;
node *res, *pre=NULL;
int c = 0;
while(p && q){
int t = p->data + q->data + c;
node *r = new node();
r->data = t%10;
if(pre){
pre->next = r;
pre = r;
}
else pre = res = r;
c = t/10;
p = p->next; q = q->next;
}
while(p){
int t = p->data + c;
node *r = new node();
r->data = t%10;
pre->next = r;
pre = r;
c = t/10;
p = p->next;
}
while(q){
int t = q->data + c;
node *r = new node();
r->data = t%10;
pre->next = r;
pre = r;
c = t/10;
q = q->next;
}
if(c>0){
node *r = new node();
r->data = c;
pre->next = r;
}
return res;
}
void print(node *head){
while(head){
cout<<head->data<<" ";
head = head->next;
}
cout<<endl;
}
int main(){
int n = 5;
int a[] = {
1, 2, 9, 9, 3
};
int m = 3;
int b[] = {
9, 9, 2
};
node *p = init(a, n);
node *q = init(b, m);
node *res = addlink(p, q);
if(p) print(p);
if(q) print(q);
if(res) print(res);
return 0;
}