Open In App
Related Articles

Data Structures | Linked List | Question 12

Like Article
Save Article
Report issue

A circularly linked list is used to represent a Queue. A single variable p is used to access the Queue. To which node should p point such that both the operations enQueue and deQueue can be performed in constant time? (GATE 2004) 


rear node


front node


not possible with a single pointer


node next to front

Answer: (A)


Answer is not \”(b) front node\”, as we can not get rear from front in O(1), but if p is rear we can implement both enQueue and deQueue in O(1) because from rear we can get front in O(1). Below are sample functions. Note that these functions are just sample are not working. Code to handle base cases is missing. 


/* p is pointer to address of rear (double pointer).  This function adds new
   node after rear and updates rear which is *p to point to new node  */
void  enQueue(struct node **p, struct node *new_node)
    /* Missing code to handle base cases like *p is NULL */
     new_node->next = (*p)->next;
     (*p)->next = new_node;
     (*p) = new_node /* new is now rear */
     /* Note that p->next is again front and  p is rear */
/* p is pointer to rear. This function removes the front element and
    returns the dequeued element from the queue */
struct node *deQueue(struct node *p)
    /* Missing code to handle base cases like p is NULL,
        p->next is NULL,...  etc */
    struct node *temp = p->next;
    p->next = p->next->next;
    return temp;
    /* Note that p->next is again front and  p is rear */



Quiz of this Question
Please comment below if you find anything wrong in the above post

Last Updated : 28 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Similar Reads