用兩個棧實現隊列--劍指offer05(java實現)

題目描述

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

解題思路

入隊列操作不變,出隊列操作由於是先進先出,故使用另一個棧將出棧元素保存在stack2中,取到最裏面的元素,再將stack1中的元素出棧存回stack1中。

源碼

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() {
        int result;
        while(stack1.size() > 0)
            stack2.push(stack1.pop());
        result = stack2.pop();
        while(stack2.size() > 0)
            stack1.push(stack2.pop());
        return result;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章