|
| 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 | +} |
0 commit comments