class Node {
constructor(value) {
this
.value = value;
this
.npx = 0;
}
}
class XorLinkedList {
constructor() {
this
.head =
null
;
this
.tail =
null
;
this
.nodes = [];
}
insert(value) {
let node =
new
Node(value);
this
.nodes.push(node);
if
(
this
.head ===
null
){
this
.tail = node;
}
if
(
this
.head !==
null
) {
node.npx = getPointer(
this
.head);
this
.head.npx = getPointer(node) ^
this
.head.npx;
}
this
.head = node;
}
printList() {
let current =
this
.head;
let prevAddr =
null
;
let output =
""
;
while
(current) {
output += current.value +
" "
;
let nextAddr = prevAddr ^ current.npx;
prevAddr = getPointer(current);
current = dereferencePointer(nextAddr);
}
console.log(output);
}
isEmpty() {
return
!
this
.head;
}
delEnd() {
if
(
this
.isEmpty()) {
return
-1;
}
else
if
(
this
.head ===
this
.tail) {
let value =
this
.head.value;
this
.head =
this
.tail =
null
;
return
value;
}
else
{
let secLastNodeId =
this
.nodes[
this
.nodes.indexOf(
this
.tail)-1];
var
res =
this
.nodes.shift();
addressMap.
delete
(
this
.tail);
delete
this
.tail;
this
.tail = secLastNodeId;
return
res;
}
}
}
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.delEnd();
if
(xll.isEmpty()) {
console.log(
"List is empty"
);
}
else
{
xll.printList();
}