225. (一个or两个)队列实现栈

在这里插入图片描述

这里写目录标题

两个队列

思路:每次把元素push进q2,然后把q1的元素push进q2,再交换q1和q2。
比如 1 2, 那么第一次q2是1, q1为空,然后交换 q1是1,q2为空
第二次 q2push了2,现在是2,q1这时候是1,然后把q1push到q2,q2就变成了2 1,此时q1为空,然后再交换q1,q2,那么q1就是 2 1,q2是空

class MyStack {
    Queue<Integer> q1;
    Queue<Integer> q2;
    /** Initialize your data structure here. */
    public MyStack() {
        q1 = new LinkedList<>();
        q2 = new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
    	// 先push进q2
        q2.offer(x);
        // 把q1的元素都push到q2
        while(!q1.isEmpty()){
            q2.offer(q1.poll());
        }
        // 交换q1和q2
        Queue<Integer> temp = q1;
        q1 = q2;
        q2 = temp;
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return q1.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return q1.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return q1.isEmpty();
    }
}

一个队列

入栈操作时,首先获得入栈前的元素个数 n,然后将元素入队到队列,再将队列中的前 n 个元素(即除了新入栈的元素之外的全部元素)依次出队并入队到队列,此时队列的前端的元素即为新入栈的元素,且队列的前端和后端分别对应栈顶和栈底 比如1 2 3
1 队列 1

2
1 队列1->先让2入队 -> 1 2 -> 1出队再入队 -> 2 1

3
2
1 队列 2 1 -> 先让3入队 -> 2 1 3 - > 2 1出队再入队 -> 3 2 1

class MyStack {
    Queue<Integer> q;
    /** Initialize your data structure here. */
    public MyStack() {
        q = new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
    	// 获得入栈前的元素n
        int n = q.size();
        q.offer(x);
        // 出队再重新入队
        for(int i = 0; i < n; i++){
            q.offer(q.poll());
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return q.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return q.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return q.isEmpty();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值