-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked-list-assignment.cpp
More file actions
91 lines (78 loc) · 2.15 KB
/
linked-list-assignment.cpp
File metadata and controls
91 lines (78 loc) · 2.15 KB
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
// Jacinta Syilloam
// 5027221036
#include <iostream>
using namespace std;
// struct for linked list node
struct ListNode
{
int val;
ListNode *next;
// constructor to initialize node with x value and no next node
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode *addNum(ListNode *l1, ListNode *l2)
{
ListNode *dummy = new ListNode(0); // create dummy list
ListNode *curr = dummy; // initialize pointer
int carry = 0; // initialize carry w 0 initially
// loop until both input list empty and no carry left
while (l1 != nullptr || l2 != nullptr || carry == 1)
{
int sum = 0; // initialize sum
if (l1 != nullptr)
{
sum += l1->val; // add l1 to sum
l1 = l1->next; // move l1
}
if (l2 != nullptr)
{
sum += l2->val; // add l2 to sum
l2 = l2->next; // move l2
}
sum += carry; // if previously have carry, add to sum
carry = sum / 10; // divide by 10 to get carry
ListNode *node = new ListNode(sum % 10); // new node of sum's last digit and attach to result
curr->next = node; // update curr to new node
curr = curr->next;
}
return dummy->next;
}
// print result
void printList(ListNode *head)
{
while (head)
{
cout << head->val; // print current node
head = head->next; // move next node
}
cout << endl;
}
// delete linked list to prevent memory leaks
void cleanMem(ListNode *head)
{
while (head)
{
ListNode *temp = head;
head = head->next;
delete temp;
}
}
int main()
{
// testcase: 2+5= 7, 4+6=1(0) 3+4=7(+1=8)
ListNode *l1 = new ListNode(2);
l1->next = new ListNode(4);
l1->next->next = new ListNode(3);
ListNode *l2 = new ListNode(5);
l2->next = new ListNode(6);
l2->next->next = new ListNode(4);
// call the addNum function to add the two linked lists
ListNode *result = addNum(l1, l2);
// print the result
printList(result);
// clean up memory to prevent memory leak
cleanMem(l1);
cleanMem(l2);
cleanMem(result);
return 0;
}