A circular queue has been implemented using a singly linked list where each node consists of a value and a single pointer pointing to the next node. We maintain exactly two external pointers FRONT and REAR pointing to the front node and the near node of the queue, respectively. Which of the following statements is/are CORRECT for such a circular queue, so that insertion and deletion operations can be performed in O(1) time? I. Next pointer of front node points to the rear node. II. Next pointer of rear node points to the front node.
A circular queue has been implemented using a singly linked list where each node consists of a value and a single pointer pointing to the next node. We maintain exactly two external pointers FRONT and REAR pointing to the front node and the near node of the queue, respectively. Which of the following statements is/are CORRECT for such a circular queue, so that insertion and deletion operations can be performed in O(1) time? I. Next pointer of front node points to the rear node. II. Next pointer of rear node points to the front node. Correct Answer II only
Solution:
Concept:
In a queue, elements are deleted from front and inserted from rear end. Whenever a new element is inserted, rear is incremented.
Explanation:
Diagram
[ alt="F1 R.S Deepak 09.12.2019 D3" src="//storage.googleapis.com/tb-img/production/19/12/F1_R.S_Deepak_09.12.2019_D3.png" style="width: 387px; height: 116px;">
So, in case of a circular queue to make an insert and delete operation in O (1) time, the rear pointer will point to the next node i.e. front node. After storing this pointer rear will point to the newly created node.
For enqueue: struct node *ptr
ptr -> next = rear -> next;
rear -> next = ptr
rear = ptr
For dequeue: ptr(front node)
rear -> next = front ->next
ptr = front
front =rear -> next
free(ptr)
Important Points:
For above enqueue and dequeue,
Assume linked list contains more than one element
Structure:
struct node
{
int data;
struct node *next;
}