-
Notifications
You must be signed in to change notification settings - Fork 0
/
addTwoNumberLinkedList.c
112 lines (106 loc) · 2.46 KB
/
addTwoNumberLinkedList.c
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <stdio.h>
#include <stdlib.h>
typedef struct elementT {
struct elementT *next;
int data;
} element;
element *addTwoNumber(element *a, element *b) {
if(a == NULL)
return b;
else if(b == NULL)
return a;
reverseLinkedList(&a);
reverseLinkedList(&b);
element *res = NULL;
int r = 0, v;
element *ea = a, *eb = b;
while(ea != NULL && eb != NULL) {
int sum = ea->data + eb->data + r;
r = sum / 10;
v = sum % 10;
element *o = (element *)malloc(sizeof(element));
o->data = v;
if(res == NULL)
res = o;
else {
element *t = res->next, *p = res;
while(t) {
p = t;
t = t->next;
}
p->next = o;
}
ea = ea->next;
eb = eb->next;
}
while(ea != NULL) {
int sum = ea->data + r;
r = sum / 10;
v = sum % 10;
element *o = (element *)malloc(sizeof(element));
o->data = v;
element *t = res->next, *p = res;
while(t) {
p = t;
t = t->next;
}
p->next = o;
ea = ea->next;
}
while(eb != NULL) {
int sum = eb->data + r;
r = sum / 10;
v = sum % 10;
element *o = (element *)malloc(sizeof(element));
o->data = v;
element *t = res->next, *p = res;
while(t) {
p = t;
t = t->next;
}
p->next = o;
eb = eb->next;
}
reverseLinkedList(&res);
return res;
}
void reverseLinkedList(element **head) {
if((*head) == NULL || (*head)->next == NULL)
return;
element *ele = *head, *next = (*head)->next;
(*head)->next = NULL;
while(next) {
element *t = next->next;
next->next = ele;
ele = next;
next = t;
}
(*head) = ele;
}
element *makeNode(int d) {
element *ele = (element *)malloc(sizeof(element));
ele->data = d;
return ele;
}
void printList(element *ele) {
while(ele) {
printf("%d ", ele->data);
ele = ele->next;
}
printf("\n");
}
main()
{
element *a = makeNode(3);
a->next = makeNode(5);
a->next->next = makeNode(7);
a->next->next->next = makeNode(9);
element *b = makeNode(1);
//b->next = makeNode(2);
//b->next->next = makeNode(3);
printList(a);
//reverseLinkedList(&a);
printList(b);
element *r = addTwoNumber(a, b);
printList(r);
}