📜  门| GATE-CS-2000 |问题 22(1)

📅  最后修改于: 2023-12-03 15:12:39.559000             🧑  作者: Mango

GATE-CS-2000 Problem 22

The GATE-CS-2000 Problem 22 is a typical problem asked in the GATE examination for computer science students. It involves implementing a queue using stacks.

Problem Statement

The problem statement asks to implement a queue data structure using two stacks, and the operations that need to be supported are: enqueue, dequeue and isEmpty.

Solution

The solution to this problem involves using two stacks, let us call them stack1 and stack2. The enqueue operation involves pushing the elements onto the stack1, and the dequeue operation involves popping the elements from stack2. However, if stack2 is empty, we need to transfer all the elements from stack1 to stack2 in reverse order so that we can pop the front element from stack2.

class QueueUsingStacks {
   private Stack<Integer> stack1 = new Stack<>();
   private Stack<Integer> stack2 = new Stack<>();
 
   public void enqueue(int x) {
      stack1.push(x);
   }
 
   public int dequeue() {
      if (stack1.empty() && stack2.empty()) {
         throw new NoSuchElementException("Cannot dequeue from an empty queue");
      }
      if (stack2.empty()) {
         while (!stack1.empty()) {
            stack2.push(stack1.pop());
         }
      }
      return stack2.pop();
   }
 
   public boolean isEmpty() {
      return stack1.empty() && stack2.empty();
   }
}

The code above implements a queue using stacks. The enqueue operation simply pushes the element onto stack1. The dequeue operation checks if both stacks are empty, and throws an exception if they are. If stack2 is empty but stack1 is not, all the elements from stack1 are transferred to stack2 in reverse order. Finally, the front element is popped off from stack2 and returned.

Conclusion

In conclusion, the GATE-CS-2000 Problem 22 is a useful exercise for implementing a queue using stacks. The solution involves using two stacks, and transferring elements from one stack to the other to achieve the required operations of enqueue, dequeue, and isEmpty.