天天看點

用兩個棧實作隊列--劍指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;
    }
}
           

繼續閱讀