-
Notifications
You must be signed in to change notification settings - Fork 344
/
Copy pathXORlist.cpp
126 lines (109 loc) · 2.06 KB
/
XORlist.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
120
121
122
123
124
125
126
// memory efficient version of doubly linked list
#include <iostream>
#include <cstdint>
#include <stdexcept>
using namespace std;
struct Node
{
int data;
Node* npx;
Node(int data)
{
(*this).data = data;
npx = NULL;
}
};
class XORlist
{
private:
Node *head;
public:
XORlist();
~XORlist();
void add_head(int data);
void display();
Node *XOR(Node *x, Node *y);
};
XORlist::XORlist()
{
head = NULL;
}
XORlist::~XORlist()
{
if (head != NULL)
{
Node *head_next = XOR(NULL, head->npx);
while (head_next != NULL)
{
Node *temp = head;
head = head_next;
head_next = XOR(temp, head->npx);
delete temp; // delete previous node of new head
}
delete head;
head = NULL;
}
}
void XORlist::add_head(int data)
{
if (head == NULL)
{
head = new Node(data);
}
else
{
Node *new_node = new Node(data);
new_node->npx = XOR(NULL, head);
head->npx = XOR(new_node, head->npx);
head = new_node;
}
}
void XORlist::display()
{
if (head == NULL)
{
throw runtime_error("head is NULL");
}
Node *prev = NULL;
Node *temp = head;
// forward traversal
while (temp != NULL)
{
cout << temp->data << " ";
Node *next = XOR(prev, temp->npx);
prev = temp;
temp = next;
}
cout << endl;
// backward traversal
// prev is pointing to last node
// temp is NULL
while (prev != NULL)
{
cout << prev->data << " ";
Node *next = XOR(temp, prev->npx);
temp = prev;
prev = next;
}
}
Node* XORlist::XOR(Node *x, Node *y)
{
return (Node*)(uintptr_t(x) ^ uintptr_t(y)); // uintptr_t to do bitwise operation on pointer
}
int main()
{
XORlist list;
list.add_head(3);
list.add_head(2);
list.add_head(1);
list.add_head(0);
try
{
list.display();
}
catch (exception &err)
{
cout << err.what() << endl;
}
return 0;
}