利用2个栈实现队列

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

基本思路:
栈是先进后出,队列是先进先出。一个栈的时候是先进先出,而当我们再使用一个栈的时候就可以颠倒进出的顺序,所以我们用一个栈保存Push的元素,另一个栈用来Pop元素,所以就可以实现先进先出。

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack1.push(node);        //stack1用来保存push的元素
    }
    
    public int pop() {
        if(stack2.empty()==false){   
            return stack2.pop();    //stack2用来保存pop的元素,当stack2不为空且调用pop方法时,直接pop stack2中的元素
        }
        while(stack1.empty()==false){
            stack2.push(stack1.pop());     //当stack2为空且调用pop方法时,要将stack1中的元素push到stack2中,然后再pop
        }
        return stack2.pop();
    }
}

猜你喜欢

转载自blog.csdn.net/ywh15387127537/article/details/84786314
今日推荐