A queue is implemented using a non-circular singly linked list. The queue has a head pointer and a tail pointer, as shown in the figure. Let n denote the number of nodes in the queue. Let enqueue be implemented by inserting a new node at the head, and dequeue be implemented by deletion of a node from the tail. Which one of the following is the time complexity of the most time-efficient implementation of enqueue and dequeue, respectively, for this data structure?
A queue is implemented using a non-circular singly linked list. The queue has a head pointer and a tail pointer, as shown in the figure. Let n denote the number of nodes in the queue. Let enqueue be implemented by inserting a new node at the head, and dequeue be implemented by deletion of a node from the tail. Which one of the following is the time complexity of the most time-efficient implementation of enqueue and dequeue, respectively, for this data structure? Correct Answer θ(1), θ(n)
Enquene: Inserting new node in front.
next = Head
Head = P
Hence two-pointer operations will take O(1) time.
Dequeue:
As the list is singly linked, we have to traverse up to the second last node for pointer manipulation, which will take O(n) time.
Enqueue:
Create a Node P.
P-->Data = Data
P-->Next = Head
Head = P
Complexity = Only pointer manipulatuon so constant = O(1)
Dequeue:temp = head;
While( temp-Next-->Next != NULL)
{
temp = temp-Next;
}
temp-->next = NULL;
Tail = temp;
Complexity = Traversing list and then free last node and keep track of Tail pointer = O(n)