-
Notifications
You must be signed in to change notification settings - Fork 0
/
7AddTwoNumbersUsingLinkedList.c
127 lines (105 loc) · 2.1 KB
/
7AddTwoNumbersUsingLinkedList.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int digit;
struct node* link;
}node;
node* digit(node* head, int dig)
{
node* temp = (node*)malloc(sizeof(node));
temp->digit = dig;
temp->link = NULL;
temp->link = head;
head = temp;
return head;
}
node* reverse(node* head)
{
if(head == NULL)
{
return head;
}
node *prev = NULL;
node* next = NULL;
while(head != NULL)
{
next = head->link;
head->link = prev;
prev = head;
head = next;
}
head = prev;
return head;
}
node* addition(node* head1, node* head2) {
head1 = reverse(head1);
head2 = reverse(head2);
node* ptr1 = head1;
node* ptr2 = head2;
node* head3 = NULL;
int sum = 0, carry = 0;
while (ptr1 != NULL || ptr2 != NULL || carry != 0)
{
sum = carry;
if (ptr1 != NULL)
{
sum += ptr1->digit;
ptr1 = ptr1->link;
}
if (ptr2 != NULL)
{
sum += ptr2->digit;
ptr2 = ptr2->link;
}
carry = sum / 10;
sum = sum % 10;
head3 = digit(head3, sum);
}
return head3;
}
void print(node* head)
{
node* ptr = head;
while(ptr != NULL)
{
printf("%d", ptr->digit);
if(ptr->link != NULL)
{
printf("->");
}
ptr = ptr->link;
}
}
int main()
{
int n1, n2;
node* head1 = (node*)malloc(sizeof(node));
head1 = NULL;
node* head2 = (node*)malloc(sizeof(node));
head2 = NULL;
node* head3 = (node*)malloc(sizeof(node));
head3 = NULL;
printf("Enter the first number: ");
scanf("%d", &n1);
printf("Enter the second number: ");
scanf("%d", &n2);
while(n1 != 0)
{
head1 = digit(head1, n1%10);
n1 = n1/10;
}
print(head1);
printf("\n");
while(n2 != 0)
{
head2 = digit(head2, n2%10);
n2 = n2/10;
}
print(head2);
printf("\n");
printf("Sum of the numbers is: ");
head3 = addition(head1, head2);
print(head3);
return 0;
}