Skip to content

Commit 045111e

Browse files
Merge pull request #472 from abhishekraj272/master
Created XOR Linked List
2 parents 71ed028 + 832e718 commit 045111e

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

Linked List/xor_linked_list.cpp

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
//Doubly Linked List cost too much space because it stores previous and next address.
2+
//So, XOR Linked List stores XOR of previous and next address and hence saves data.
3+
4+
#include <iostream>
5+
#include <cstdint> // for including "uintptr_t" data structure.
6+
7+
using namespace std;
8+
9+
//Node is defined here and constructor is created.
10+
class Node {
11+
public:
12+
int data;
13+
Node *link;
14+
15+
Node(int info) {
16+
data = info;
17+
link = NULL;
18+
}
19+
};
20+
21+
//function returns XOR of previous and next pointer.
22+
Node* XOR(Node *a, Node *b) {
23+
//uintptr_t stores XOR of address.
24+
return (Node*)((uintptr_t)(a) ^ (uintptr_t)(b));
25+
}
26+
27+
//function to create a node at beginning.
28+
void push(Node **head, int data) {
29+
Node *temp = new Node(data);
30+
31+
//link stores XOR of head address and NULL.
32+
temp->link = XOR(*head, NULL);
33+
34+
if ((*head) != NULL) {
35+
//if head != NULL link stores XOR of prev and next node.
36+
(*head)->link = XOR(temp, XOR((*head)->link, NULL));
37+
}
38+
39+
(*head) = temp;
40+
41+
}
42+
43+
void print(Node *head) {
44+
Node *curr = head;
45+
Node *prev = NULL;
46+
Node *next;
47+
48+
while(curr != NULL) {
49+
cout << curr->data << " ";
50+
51+
next = XOR(prev, curr->link);
52+
53+
prev = curr;
54+
55+
curr = next;
56+
}
57+
}
58+
59+
int main() {
60+
Node *head;
61+
push(&head, 1);
62+
push(&head, 2);
63+
push(&head, 3);
64+
push(&head, 4);
65+
push(&head, 5);
66+
push(&head, 6);
67+
print(head);
68+
69+
}

0 commit comments

Comments
 (0)