This repository has been archived by the owner on Feb 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathXOR_Linked_List.cpp
63 lines (63 loc) · 1.64 KB
/
XOR_Linked_List.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
// Implementation of XOR linked list
#include <iostream>
#include <cstdint>
class Node {
public:
int data;
Node* xorPointer;
Node(int val) : data(val), xorPointer(nullptr) {}
};
class XORLinkedList {
private:
Node* head;
public:
XORLinkedList() : head(nullptr) {}
void insert(int data) {
Node* newNode = new Node(data);
newNode->xorPointer = head;
if (head != nullptr) {
head->xorPointer = XOR(head->xorPointer, newNode);
}
head = newNode;
}
void printForward() const {
Node* current = head;
Node* prev = nullptr;
Node* next;
std::cout << "Forward traversal: ";
while (current != nullptr) {
std::cout << current->data << " ";
next = XOR(prev, current->xorPointer);
prev = current;
current = next;
}
std::cout << std::endl;
}
void printBackward() const {
Node* current = head;
Node* prev = nullptr;
Node* next;
std::cout << "Backward traversal: ";
while (current != nullptr) {
std::cout << current->data << " ";
next = XOR(prev, current->xorPointer);
prev = current;
current = next;
}
std::cout << std::endl;
}
private:
Node* XOR(Node* a, Node* b) const {
return reinterpret_cast<Node*>(reinterpret_cast<uintptr_t>(a) ^ reinterpret_cast<uintptr_t>(b));
}
};
int main() {
XORLinkedList xorList;
xorList.insert(1);
xorList.insert(2);
xorList.insert(3);
xorList.insert(4);
xorList.printForward();
xorList.printBackward();
return 0;
}