[劍指offer] 用兩個棧實現隊列

本文首發於我的個人博客:尾尾部落

題目描述

用兩個棧來實現一個隊列,完成隊列的Push和Pop操作。 隊列中的元素爲int類型。

解題思路

兩個棧 stack1 和 stack2:

  • push 動作都在 stack1 中進行,
  • pop 動作在 stack2 中進行。當 stack2 不爲空時,直接 pop,當 stack2 爲空時,先把 stack1 中的元素 pop 出來,push 到 stack2 中,再從 stack2 中 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() {
        if(stack1.isEmpty() && stack2.isEmpty())
            throw new RuntimeException("Queue is empty!");
        int node;
        if(stack2.isEmpty()){
            while(!stack1.isEmpty()){
                node = stack1.pop();
                stack2.push(node);
            }
        }
        return stack2.pop();

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章