Buy/Download all MCQ Ebook >>>Click Here<<<
Data Structure Questions and AnswersStack using Queues
Click on any option to know the CORRECT ANSWERS
Question 1 
To implement a stack using queue(with only enqueue and dequeue operations), how many queues will you need?
1  
2  
3  
4 
Question 1 Explanation:
Either the push or the pop has to be a costly operation, and the costlier operation requires two queues.
Question 2 
Making the push operation costly, select the code snippet which implements the same.(let q1 and q2 be two queues)
public void push(int x) { if(empty()) { q1.offer(x); } else{ if(q1.size()>0  
public void push(int x) { if(empty()) { q1.offer(x); } else { if(q1.size()>0  
public void push(int x) { if(empty()) { q1.offer(x); } else { if(q1.size()>0  
None of the mentioned 
Question 2 Explanation:
Stack follows LIFO principle, hence a new item added must be the first one to exit, but queue follows FIFO principle, so when a new item is entered into the queue, it will be at the rear end of the queue. If the queue is initially empty, then just add the new element, otherwise add the new element to the second queue and dequeue all the elements from the second queue and enqueue it to the first one, in this way, the new element added will be always in front of the queue. Since two queues are needed to realize this push operation, it is considered to be costlier.
Question 3 
Making the push operation costly, select the code snippet which implements the pop operation.
public void pop() { if(q1.size()>0) { q2.poll(); } else if(q2.size()  
public void pop() { q1.poll(); q2.poll(); }  
None of the mentioned

Question 3 Explanation:
As the push operation is costly, it is evident that the required item is in the front of the queue, so just dequeue the element from the queue.
Question 4 
Select the code snippet which returns the top of the stack.
public int top() { if(q1.size()>0) { return q1.poll(); } else if(q2.size()  
public int top() { if(q1.size()==0) { return q1.peek(); } else if(q2.size  
public int top() { if(q1.size()>0) { return q1.peek(); } else if(q2.size()  
None of the mentioned

Question 4 Explanation:
Assuming its a push costly implementation, the top of the stack will be in the front end of the queue, note that peek() just returns the front element, while poll() removes the front element from the queue.
Question 5 
Select the code snippet which return true if the stack is empty, false otherwise.
public boolean empty() { return q2.isEmpty(); }  
public boolean empty() { return q1.isEmpty()  q2.isEmpty(); }  
public boolean empty() { return q1.isEmpty(); }  
public boolean empty() { return q1.isEmpty() & q2.isEmpty(); } 
Question 5 Explanation:
If both the queues are empty, then the stack also is empty.
There are 5 questions to complete.