Question
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?
Official answer and solution
- Official answer
- B
- From
- Official GATE 2018 answer key
Solution
Analyze head insertion and tail deletion in a non-circular singly linked list.
Enqueue is implemented by inserting a new node at head:
- Allocate the new node, point its
nextpointer tohead, and updateheadto the new node. - This requires a constant number of pointer assignments, running in time.
Dequeue is implemented by deleting the node at tail:
- To delete the tail node, the
nextpointer of the -th node (the node immediately precedingtail) must be set toNULL, andtailmust be updated to point to this node. - In a singly linked list with only forward pointers, the predecessor of
tailcannot be reached directly fromtail. - Finding the -th node requires traversing the list starting from
head, which visits nodes and takes time.
Therefore, the time complexities are for enqueue and for dequeue.
B
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2018 Computer Science and Information Technology (CS)
- Question
- 13 of 65, printed as CS Q.3
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.