Leetcode_#232_用棧實現隊列

原題:#232_用棧實現隊列

  • 棧:先進後出
  • 隊列:先進先出
  • 使用兩個棧A,B。進棧時進入A,出棧時先從A出,進入B,再從B出。這時就可以實現先進先出了
class MyQueue {
    private Stack<Integer> in = new Stack<>();
    private Stack<Integer> out = new Stack<>();
    public void push(int x) {
        in.push(x);
    }
    public int pop() {
        in2out();
        return out.pop();
    }
    public int peek() {
        in2out();
        return out.peek();
    }
    private void in2out() {
        if (out.isEmpty()) {
            while (!in.isEmpty()) {
                out.push(in.pop());
            }
        }
    }
    public boolean empty() {
        return in.isEmpty() && out.isEmpty();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章