232 views
7 7 votes

A FIFO queue is represented using a circular linked list and only one external pointer $\text{Q}$.

  • Design $1: \text{Q}$ points to the node containing the front item.
     
  • Design $2: \text{Q}$ points to the node containing the rear item.

Which design is better?

  1. Design $1$ is better.
     
  2. Design $2$ is better.
     
  3. Both are the same.
     
  4. $\text{Q}$ should point to the middle node.
     
  5. A circular linked list cannot be used to represent a FIFO queue.

3 Answers

1 1 vote

If $\text{Q}$ points to the rear node, then:

front node = Q->next
rear node  = Q

Enqueue can be done after the rear node in $\text{O}(1)$ time.

Dequeue can remove $\text{Q} \rightarrow \text{next}$, which is the front node, also in $\text{O}(1)$ time.

If $\text{Q}$ points to the front node, then reaching the rear node may require traversal.

So the better design is to keep $\text{Q}$ pointing to the rear node.

Correct option: B

0 0 votes

Say the queue currently has 10, 20, 30 (10 is front, 30 is rear).

Enqueue(40) add 40 to the rear
newNode(40)->next = Q->next(10)
Q->next(30's next) = newNode(40)
Q = newNode // now rear at 40
now 10-20-30-40-10 ...In O(1)
  
Dequeue(10)

temp = q.next // store 10
q.next = q.next.next // rear next is to 20
temp.next = null;

now 20-30-40-20..In (O(1))
As both the enque and deque is done in O(1) , what exactly is done in normal queue..so it's the best Design..

0 0 votes

Design 1: Q points to the node containing the front item. Then inserting into the rear would take linear time, having to scan through all the elements to find the rear node with repeated $curr\to next == Q$, then we can insert in the rear.

Design 2: Q points to the node containing the rear item. Then insert rear is simple, and to get front, we just have to look at the next element, and removing it also would be easier since the rear element is the previous element of the front element.

Answer: B

Answer:
Position:
Show:

Related questions

4 4 votes
2 2 answers
236
236 views
GO Classes asked Jul 8
236 views
Suppose a circular queue of capacity $(n - 1)$ elements is implemented with an array of $n$ elements.Insertion and deletion operations are carried out using $\texttt{REAR...
8 8 votes
3 3 answers
355
355 views
GO Classes asked Jul 8
355 views
A queue is implemented using two stacks $\text{S1}$ and $\text{S2}$.Use the implementation where $\texttt{dequeue()}$ is $\text{O(1)}$ by keeping the front of the queue a...
8 8 votes
2 2 answers
259
259 views
GO Classes asked Jul 8
259 views
Consider an array implementation of a queue. Suppose we try to keep all items at the front of a partially-filled array, so that $\texttt{data[0]}$ is always the front of ...
6 6 votes
3 3 answers
224
224 views
GO Classes asked Jul 8
224 views
Consider an initially empty stack $\text{S}$ and an initially empty queue $\text{Q}$.The following operations are performed:S.push(5) S.push(6) S.push(S.top()) S.push(7) ...