-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4_9-10_integer_linked_list_fake.cpp
122 lines (94 loc) · 2.12 KB
/
4_9-10_integer_linked_list_fake.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
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
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
struct listNode {
int num;
listNode * next;
};
typedef listNode * intLinkedList;
void printInteger(intLinkedList integer);
intLinkedList intToList(int num);
intLinkedList sumIntLists(intLinkedList integer1, intLinkedList integer2);
void removeLinkedList(intLinkedList &head);
int main()
{
int num1 = 78;
int num2 = 14;
intLinkedList integer1 = intToList(num1);
intLinkedList integer2 = intToList(num2);
intLinkedList sum = sumIntLists(integer1, integer2);
cout << "\nInteger one: ";
printInteger(integer1);
cout << "\nInteger two: ";
printInteger(integer2);
cout << "\nTheir sum is: ";
printInteger(sum);
removeLinkedList(integer1);
removeLinkedList(integer2);
removeLinkedList(sum);
cin.get();
return 0;
}
// Exercise 4.9
intLinkedList intToList(int num)
{
if (num < 0)
{
num = 0;
}
intLinkedList head = nullptr;
do {
listNode * newNode = new listNode;
newNode->num = num % 10;
num /= 10;
newNode->next = head;
head = newNode;
} while (num);
return head;
}
// Exercise 4.10
intLinkedList sumIntLists(intLinkedList integer1, intLinkedList integer2)
{
int num1 = 0;
int num2 = 0;
int sum = 0;
listNode * loopPtr = integer1;
while (loopPtr != nullptr)
{
num1 *= 10;
num1 += loopPtr->num;
loopPtr = loopPtr->next;
}
loopPtr = integer2;
while (loopPtr != nullptr)
{
num2 *= 10;
num2 += loopPtr->num;
loopPtr = loopPtr->next;
}
sum = num1 + num2;
return intToList(sum);
}
void printInteger(intLinkedList integer)
{
listNode * loopPtr = integer;
while (loopPtr != nullptr)
{
cout << loopPtr->num;
loopPtr = loopPtr->next;
}
}
void removeLinkedList(intLinkedList &head)
{
listNode * loopPtr = head;
listNode * deleteNode;
while (loopPtr != nullptr)
{
deleteNode = loopPtr;
loopPtr = loopPtr->next;
delete deleteNode;
}
head = nullptr;
return;
}