Is it necessary to have a tail pointer in doubly linked list? How to implement doubly linked list insertion without tail pointer, what would be the time complexity if we do so.
2 Answers
If you know the node you're inserting before or after, then complexity is O(1). You only set the pointers in the previous/next nodes to point to the new node, and set the pointers in the new node to the prev/next nodes. You also update the head pointer if insertion is to the beginning of the list.
If you do not have a tail pointer in a doubly-linked list (or singly-linked list) and you do not have a reference to the last element, then appending to the list becomes O(n) because you have to traverse the list to find the last element.
Comments
No, it is not necessary. Below are the time complexities for a doubly-linked list that does not utilize tail pointers.
Prepending to a List: O(1)
(head <-> newNode <-> x)
Inserting between two nodes in the List: O(n)
(head <-> x <-> newNode <-> y)
Appending to a List: O(n)
(head <-> x <-> y <-> newNode)
Note: Utilizing the
tailof a doubly-linked list would make the complexity O(1)
TL;DR: No, it would function almost the same, except for less performant appending cases O(n).