Implementation of XOR Linked List in Python
Prerequisite: XOR Linked List
An ordinary Doubly Linked List requires space for two address fields to store the addresses of previous and next nodes. A memory-efficient version of Doubly Linked List can be created using only one space for the address field with every node. This memory efficient Doubly Linked List is called XOR Linked List or Memory Efficient as the list uses bitwise XOR operation to save space for one address. In the XOR linked list, instead of storing actual memory addresses, every node stores the XOR of addresses of previous and next nodes.
The XOR Linked List implementation in Python is not of much use because the Python garbage collector doesn’t allow to save the node whose address is being XORed.
The functions that are implemented in the below program are:
- InsertAtStart(): Method to insert a node at the beginning.
- InsertAtEnd(): Method to insert a node at the end.
- DeleteAtStart(): Method to delete a node at the beginning.
- DeleteAtEnd(): Method to delete a node at the end.
- Print(): Method to traverse through the linked list from beginning to end.
- ReversePrint(): Method to traverse through the linked list from end to the beginning.
- Length(): Method to return the size of the linked list.
- PrintByIndex(): Method to return the data value of the node of the linked list specified by a particular index.
- isEmpty(): Method to check if the linked list is empty or not.
- __type_cast(): Method to return a new instance of type which points to the same memory block.
Below is the complete Python program to implement XOR Linked List with the above methods:
Length: 6 Traverse linked list: 6 0 2 3 4 55 Traverse in reverse order: 55 4 3 2 0 6 Nodes: Data value at index 0 is 6 Data value at index 1 is 0 Data value at index 2 is 2 Data value at index 3 is 3 Data value at index 4 is 4 Data value at index 5 is 55 Delete Last Node: 55 Delete First Node: 6 Updated length: 4 Nodes: Data value at index 0 is 0 Data value at index 1 is 2 Data value at index 2 is 3 Data value at index 3 is 4 Traverse linked list: 0 2 3 4 Traverse in reverse order: 4 3 2 0
In Python garbage collector collect nodes and decrease the reference count of the object of a node when the object of the node is XORed, Python thinks there is no way to access the node so we used the __in which we store objects of node just for preventing it to become garbage.