Queue Quiz
1. Following is C-like pseudo-code of a function that takes a Queue as an argument, and uses a stack S to do processing.
void fun(Queue *Q)
{
Stack S; // Say it creates an empty stack S
// Run while Q is not empty
while (!isEmpty(Q))
{
// deQueue an item from Q and push the dequeued item to S
push(&S, deQueue(Q));
}
// Run while Stack S is not empty
while (!isEmpty(&S))
{
// Pop an item from S and enqueue the popped item to Q
enQueue(Q, pop(&S));
}
}
-
Options:
- A) Removes the last from Q
- B) Keeps the Q same as it was before the call
- C) Makes Q empty
- D) Reverses the Q
-
Answer: D) Reverses the Q
-
Explanation:
The function uses a stack to reverse the queue. First, all elements are dequeued from the queue and pushed into the stack. Then, elements are popped from the stack and enqueued back into the queue. Since the stack follows LIFO order, the queue is reversed.
2. How many stacks are needed to implement a queue? Consider the situation where no other data structure like arrays or linked lists is available to you.
-
Options:
- A) 1
- B) 2
- C) 3
- D) 4
-
Answer: B) 2
-
Explanation:
To implement a queue using stacks, two stacks are required. One stack is used for enqueuing elements, and the other is used for dequeuing them.
3. Which of the following operations on a queue data structure has a time complexity of O(1)?
-
Options:
- A) Enqueue
- B) Dequeue
- C) Peek
- D) Clear
-
Answer: A and B
-
Explanation:
Both enqueue and dequeue operations in a standard queue have a time complexity of O(1) as they involve simple pointer adjustments.