[leetcode] 225. Implement Stack Using Queues

方法一. 使用两个单端队列

思路是让 q1 的元素永远跟 我们的 Stack 保持一致.
push 的时候 使用辅助队列 q2
1. 先把元素加入 q2
2. 之后再把 q1 中的元素依次加入 q2
3. 在交换 q1 q2 使得其定义保持一致

class MyStack {
    private Queue<Integer> q1; // Same elements as our stack
    private Queue<Integer> q2; // Auxiliary Queue.

    public MyStack() {
        q1 = new LinkedList<>();
        q2 = new LinkedList<>();
    }
    
    public void push(int x) {
        q2.offer(x);
        while (!q1.isEmpty()) {
            q2.offer(q1.poll());
        }
        Queue<Integer> tempQ;
        tempQ = q1;
        q1 = q2;
        q2 = tempQ;
    }
    
    public int pop() {
        return q1.poll();
    }
    
    public int top() {
        return q1.peek();
    }
    
    public boolean empty() {
        return q1.isEmpty();
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */

方法二. 使用一个双端队列

思路是 push 就加入队尾
pop就把队头的元素全部放在队尾,留最后一个元素再 pop
top 是队尾的元素(最后入队)

class MyStack {
    private Deque<Integer> q1;
    public MyStack() {
        q1 = new ArrayDeque<>();
    }
    
    public void push(int x) {
        q1.addLast(x);
    }
    
    public int pop() {
        int size = q1.size();
        size--;
        while(size-- > 0) {
            q1.addLast(q1.pollFirst());
        }
        return q1.pollFirst();
    }
    
    public int top() {
        return q1.peekLast();
    }
    
    public boolean empty() {
        return q1.isEmpty();
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值