天天看點

劍指offer.JZ5用兩個棧實作隊列

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

解決思路:
	當stack2不為空時,在stack2中的棧頂元素是最先進入隊列的元素,可以彈出;
	當stack2為空時,先将stack1中的元素逐個彈出并壓入stack2,再彈出棧頂元素。
code:
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(stack2.isEmpty()){
            while(!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }   
        }
        return stack2.pop();
    }
}