In the previous post, we discussed how a Doubly Linked can be created using only one space for address field with every node. In this post, we will discuss the implementation of memory efficient doubly linked list. We will mainly discuss the following two simple functions.
1) A function to insert a new node at the beginning.
2) A function to traverse the list in forward direction.
In the following code, insert() function inserts a new node at the beginning. We need to change the head pointer of Linked List, that is why a double pointer is used (See this). Let us first discuss few things again that have been discussed in the previous post. We store XOR of next and previous nodes with every node and we call it npx, which is the only address member we have with every node. When we insert a new node at the beginning, npx of new node will always be XOR of NULL and current head. And npx of the current head must be changed to XOR of new node and node next to the current head.
printList() traverses the list in forward direction. It prints data values from every node. To traverse the list, we need to get pointer to the next node at every point. We can get the address of next node by keeping track of current node and previous node. If we do XOR of curr->npx and prev, we get the address of next node.
Following are the nodes of Linked List: 40 30 20 10
Note that XOR of pointers is not defined by C/C++ standard. So the above implementation may not work on all platforms.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- Memory efficient doubly linked list
- Difference between Singly linked list and Doubly linked list
- Construct a Doubly linked linked list from 2D Matrix
- Convert Singly Linked List to XOR Linked List
- Convert a given Binary Tree to Doubly Linked List | Set 1
- Convert a given Binary Tree to Doubly Linked List | Set 2
- Convert a given Binary Tree to Doubly Linked List | Set 3
- Convert a given Binary Tree to Doubly Linked List | Set 4
- Doubly Circular Linked List | Set 1 (Introduction and Insertion)
- Doubly Circular Linked List | Set 2 (Deletion)
- Doubly Linked List | Set 1 (Introduction and Insertion)
- Convert a given Binary Tree to Circular Doubly Linked List | Set 2
- Reverse a Doubly Linked List | Set-2
- Reverse a Doubly Linked List | Set 4 (Swapping Data)
- Sort the biotonic doubly linked list | Set-2
- Given a set, find XOR of the XOR's of all subsets.
- Reverse a Doubly Linked List
- Delete a node in a Doubly Linked List
- QuickSort on Doubly Linked List