class Node {
constructor(data) {
this
.data = data;
this
.npx = 0;
}
}
class XorLinkedList {
constructor() {
this
.head =
null
;
this
.nodes = [];
}
insert(data) {
let node =
new
Node(data);
this
.nodes.push(node);
if
(
this
.head !==
null
) {
node.npx = getPointer(
this
.head);
this
.head.npx = getPointer(node) ^
this
.head.npx;
}
this
.head = node;
}
removeHead() {
if
(!
this
.head) {
console.log(
"List Is Empty"
);
return
;
}
let nextNodeId =
this
.head.npx;
if
(nextNodeId !== 0) {
let nextNode = dereferencePointer(nextNodeId);
nextNode.npx ^= getPointer(
this
.head);
delete
this
.nodes[
this
.nodes.indexOf(
this
.head)];
delete
this
.head;
this
.head = nextNode;
}
}
printList() {
let current =
this
.head;
let prevAddr = 0;
while
(current !=
null
) {
console.log(current.data);
let nextAddr = prevAddr ^ current.npx;
prevAddr = getPointer(current);
current = dereferencePointer(nextAddr);
}
}
}
let addressMap =
new
Map();
let addressCount = 1;
function
getPointer(object) {
if
(addressMap.has(object))
return
addressMap.get(object);
let newAddressCountValue = addressCount++;
addressMap.set(object, newAddressCountValue);
return
newAddressCountValue;
}
function
dereferencePointer(address) {
for
(let [key, value] of addressMap.entries()) {
if
(value === address)
return
key;
}
return
undefined
}
let xll =
new
XorLinkedList();
xll.insert(10);
xll.insert(20);
xll.insert(30);
xll.insert(40);
xll.removeHead();
xll.printList();