Skip to content

Commit 92d74ad

Browse files
committed
Add XOR-Linked-List
1 parent 67e156c commit 92d74ad

File tree

4 files changed

+91
-0
lines changed

4 files changed

+91
-0
lines changed

XOR-Linked-List/Includes.hpp

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#ifndef INC
2+
#define INC
3+
4+
#include <iostream>
5+
#include <string>
6+
using std::cout;
7+
using std::cin;
8+
9+
10+
#endif

XOR-Linked-List/Src.cpp

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
#include "./Structure.hpp"
2+
3+
/*
4+
* Next Node: XOR(prev, currentNode->npx);
5+
* Prev Node: XOR(next, currentNode->npx);
6+
*/
7+
8+
Node *XOR(Node *A, Node *B) {
9+
return (Node *) ((uintptr_t)(A) ^ (uintptr_t)(B));
10+
}
11+
12+
Node *returnLastNode(Node *head) {
13+
Node *prev = nullptr, *current = head, *next;
14+
15+
next = XOR(prev, current->npx);
16+
while (next) {
17+
next = XOR(prev, current->npx);
18+
prev = current;
19+
current = next;
20+
}
21+
return prev;
22+
}
23+
24+
void Insert(Node **head, int data) {
25+
Node *newNode = new Node();
26+
newNode->dt = data;
27+
28+
newNode->npx = XOR(*head, nullptr);
29+
30+
if (*head) {
31+
Node *next = XOR((*head)->npx, nullptr);
32+
(*head)->npx = XOR(newNode, next);
33+
}
34+
*head = newNode;
35+
}
36+
37+
void printLLBackward(Node *head) {
38+
Node *next = nullptr, *current = head, *prev;
39+
40+
while (current) {
41+
cout << current->dt << " ";
42+
43+
prev = XOR(next, current->npx);
44+
next = current;
45+
current = prev;
46+
}
47+
return;
48+
}
49+
50+
void printLLForward(Node *head) {
51+
Node *prev = nullptr, *current = head, *next;
52+
53+
while (current) {
54+
cout << current->dt << " ";
55+
56+
next = XOR(prev, current->npx);
57+
prev = current;
58+
current = next;
59+
}
60+
return;
61+
}
62+
63+
int main() {
64+
Node *head = nullptr;
65+
66+
Insert(&head, 5);
67+
Insert(&head, 8);
68+
Insert(&head, 2);
69+
70+
71+
printLLForward(head); // nullptr <-> 2 <-> 8 <-> 5 <-> nullptr
72+
73+
printLLBackward(returnLastNode(head)); // nullptr <-> 5 <-> 8 <-> 2 <-> nullptr
74+
}

XOR-Linked-List/Structure.hpp

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#include "./Includes.hpp"
2+
3+
struct Node {
4+
int dt;
5+
Node *npx;
6+
};
7+

XOR-Linked-List/a.out

22.5 KB
Binary file not shown.

0 commit comments

Comments
 (0)