-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLinkedList.cpp
More file actions
132 lines (109 loc) · 2.4 KB
/
Copy pathLinkedList.cpp
File metadata and controls
132 lines (109 loc) · 2.4 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
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
128
129
130
131
132
#include "LinkedList.h"
// Default Linked list constructor
LinkedList::LinkedList()
{
count = 0;
head = nullptr;
}
// Node constructor
LinkedList::Node::Node(int data)
{
this->data = data;
this->both = nullptr;
}
// Probably the main code of the program: calculates the xor between two
// addresses of two Nodes.
LinkedList::Node *LinkedList::xorCalc(Node *a, Node *b)
{
return (Node*) ((uintptr_t) a ^ (uintptr_t) b);
}
// Adds a node at either the head or the tail
void LinkedList::add(int data)
{
Node *temp = head;
Node *newPtr = new Node(data);
if (head == nullptr)
{
head = tail = newPtr;
}
else
{
newPtr->both = xorCalc(tail, nullptr);
tail->both = xorCalc(newPtr, xorCalc(tail->both, nullptr));
tail = newPtr;
}
count++;
}
int LinkedList::getCount()
{
return count;
}
// Goes through list iteratively and prints each node
void LinkedList::printList()
{
Node *curr = head;
Node *prev = nullptr, *next = nullptr;
while(curr != nullptr)
{
cout << curr->data << endl;
next = xorCalc(prev, curr->both);
prev = curr;
curr = next;
}
}
void LinkedList::printListReverse()
{
Node *curr = tail;
Node *prev = nullptr, *next = nullptr;
while (curr != nullptr)
{
cout << curr->data << endl;
next = xorCalc(prev, curr->both);
prev = curr;
curr = next;
}
}
// Retuns a node at an index
LinkedList::Node *LinkedList::get(int index)
{
Node *curr = head;
Node *prev = nullptr, *next = nullptr;
if (index > count)
throw -1;
for (int i = 0; i < index; i++)
{
next = xorCalc(prev, curr->both);
prev = curr;
curr = next;
}
return curr;
}
int & LinkedList::operator[](unsigned int index)
{
Node *curr = head;
Node *prev = nullptr, *next = nullptr;
if (index > count)
throw -1;
for (int i = 0; i < index; i++)
{
next = xorCalc(prev, curr->both);
prev = curr;
curr = next;
}
return curr->data;
}
// Goes through list iteratively and deletes all of the nodes
LinkedList::~LinkedList()
{
Node *curr = head;
Node *prev = nullptr, *next = nullptr;
if (head == nullptr)
return;
while(curr != nullptr)
{
next = xorCalc(prev, curr->both);
prev = curr;
delete curr;
curr = next;
}
}