题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

思路:用两个栈来模拟队列,一个栈作为存储,另一个栈作为交换空间。队列的push操作就直接push到第一个栈中,队列的pop操作,需要取得第一个栈低的元素,所以先把第一个栈的元素出栈,入栈到第二个队列,那么取的元素就是第二个栈的栈顶,第二个栈直接出栈即可。然后把剩下的数据在还原回去。

实现代码:

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() {
        while(!stack1.isEmpty()) {
            stack2.push(stack1.pop());
        }
        
        int ret = stack2.pop();
        
        while(!stack2.isEmpty()) {
            stack1.push(stack2.pop());
        }
        
        return ret;
    }
}

 

相关文章:

  • 2021-07-06
  • 2021-05-26
  • 2022-12-23
  • 2021-08-22
  • 2021-08-23
  • 2021-12-28
猜你喜欢
  • 2021-11-08
  • 2021-07-31
  • 2022-12-23
  • 2021-05-23
  • 2022-12-23
  • 2021-05-31
相关资源
相似解决方案