Issue traversing an XORLinkedList to add Nodes

52 Views Asked by At

context
An XOR linked list is a more memory efficient doubly linked list. Instead of each node holding next and prev fields, it holds a field named both, which is an XOR of the next node and the previous node. Implement an XOR linked list; it has an add(element) which adds the element to the end, and a get(index) which returns the node at index.

class Node {
    constructor(value){
        this.value = value;
        this.both = 0;
    }
}

class XORLinkedList {
    constructor(value){
        this.head = new Node(value);
    }

    add(element){
        let prev = this.head;
        // next of headNode will be currNode
        let currNode = null ^ this.head.both;
        while (currNode.both != 0){
            const next = prev ^ currNode.both;
            prev = currNode;
            currNode = next;
            }

        currNode.value = element;
        currNode.both = prev ^ null;
        }

    get(index) {
        let prev = null;
        let currNode = this.head;
        for (let i = 0; i < index; i += 1) {
          const temp = currNode;
          currNode = prev ^ this.head.both;
          prev = temp;
        }
        return currNode;
      }
}

// Driver program
const XLList = new XORLinkedList(3);
XLList.add(5);
XLList.add(7);
console.log(XLList.get(1));
console.log('end');
>>>node XORLinkedList.js
// returns nothing indefinitely, expected a node object with the value 5, prev of 3 and next of 7 and a end message

XORLinkedlist made in JS without explicit pointers. I am testing the add and get methods in the driver program and I want to know if the list traversing is working correctly or not because the get is not returning anything

0

There are 0 best solutions below