剑指Offer-Java-用两个栈实现队列

版权声明:本文为博主原创文章,转载请注明出处! https://blog.csdn.net/qq_38345606/article/details/82224165

题目

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

代码

只需要来回倒就可以实现了。

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() {
       //先把1中的全部放到2中
       while(!stack1.empty()){
           stack2.push(stack1.pop());
       }
       //2的栈顶就是队列的头
       int val = stack2.pop();
       //再把2倒回到1中
       while(!stack2.empty()){
           stack1.push(stack2.pop());
       }
       return val;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38345606/article/details/82224165