0
点赞
收藏
分享

微信扫一扫

力扣232(用栈实现队列)

南陵王梁枫 2022-01-31 阅读 76

力扣232(用栈实现队列)


解题思路

  1. 因为要用栈实现队列,所以我们必须熟知栈和队列的结构特点以及它们的常用功能。
  2. 用两个栈实现一个队列
  3. 第一个栈用于“入队”,我们相当于面向过程编程,即对我们来说就是第一个栈用于压栈,第二个栈用于出栈。
  4. 之所以符合3就能实现队列是因为:将栈1内的元素逐一出栈并压入栈2内,就可以实现原本栈1内的元素摆放顺序发生颠倒,即用两个栈实现先进栈的元素能够来到栈顶并做到先进先出的目的。
public class MyQueue {
    Stack<Integer> stack1;
    Stack<Integer> stack2;
    public MyQueue() {
        stack1=new Stack<>();
        stack2=new Stack<>();
    }

    public void push(int x) {
        stack1.push(x);
    }

    public int pop() {
        if(!stack2.isEmpty()){
            return stack2.pop();
        }else{
            while(!stack1.isEmpty()){
                int topValue=stack1.pop();
                stack2.push(topValue);
            }
            return stack2.pop();
        }
    }

    public int peek() {
        if(!stack2.isEmpty()){
            return stack2.peek();
        }else{
            while(!stack1.isEmpty()){
                int topValue=stack1.pop();
                stack2.push(topValue);
            }
            return stack2.peek();
        }

    }

    public boolean empty() {
        return stack1.isEmpty()&&stack2.isEmpty();
    }
}
举报

相关推荐

0 条评论