Linked List
Doubly Linked List
Doubly linked list (DLL) is a type of linked list in which each node apart from
storing its data has two links. The first link points to the previous node in
the list and the second link points to the next node in the list. The first
node of the list has its previous link pointing to NULL similarly the last node
of the list has its next node pointing to NULL.
Advantages vs singly linked list
- A DLL can be traversed in both forward and backward direction.
- The delete operation in DLL is more efficient if pointer to the node to be deleted is given.
- We can quickly insert a new node before a given node. In singly linked list, to delete a node, a pointer to the previous node is needed. To get this previous node, sometimes the list is traversed. In DLL, we can get the previous node using the “previous” pointer.
Disadvantages vs singly linked list
- Every node of DLL require extra space for a previous pointer
- All operations require the “previous” pointer to be maintained. This means with each operation, both the “next” pointer and the “previous” pointer need to be altered.
Node Insertion
There are 4 ways a new node can be added to a DLL:
There are 4 ways a new node can be added to a DLL:
1. At the front
of the DLL:
In this
method, the new node is always added before the head of the given linked list.
This node then becomes the new head of the linked list, replacing the previous
head as the first node.
In this
method, the new node is always added after the tail of the given linked list.
Similar to the previous method, the new node becomes the new tail of the linked
list, replacing the previous tail as the last node.
3. After a given
node
In this method,
we will be given a pointer to a node as ‘prev_node’. The new node will later be
inserted after the given node in the linked list.
4. Before a given node
In this method, we will also be given a pointer to a node as ‘next_node’. The code will check whether ‘next_code’ is NULL. If it is, the code returns as new nodes can not be added before a NULL. If it isn’t, the code inserts the new node before ‘next node’.
Circular Linked List
Circular linked list is a linked list where all nodes are connected to form a circle. There is no NULL at the end or the front. A circular linked list can be both singly circular linked or doubly circular linked.
In a circular linked list, any node can act as a head as there is no real definition of a 'head' if all nodes are connected in the same way. The only way to define a 'head' when traversing a circular linked list is to stop when the first node visited is reached again (i.e. made a full rotation of the circular linked list 'circle').
Comments
Post a Comment