Implementing a queue with two stacks

Topic description: Use two stacks to implement a queue to complete the Push and Pop operations of the queue. The elements in the queue are of type int.

Problem solving ideas:

stack1 is used to push the stack; stack2 is used to pop the stack (if stack2 is not empty, the element will be popped directly; if stack2 is empty, the element in stack1 will be popped and stored in stack2 and then popped).

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack1.push(node);
    }
    
    public int pop() {
      if(stack2.isEmpty()){
            while(!stack1.isEmpty()){
                stack2.push(stack1.pop());
            } }
            return stack2.pop();
        }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324825375&siteId=291194637