算法练习 Day10 | leetcode 232.用栈实现队列,225. 用队列实现栈

一、算法题

232.用栈实现队列

题目链接

class MyQueue {
    Stack<Integer> in;
    Stack<Integer> out;

    public MyQueue() {
        in=new Stack<>();
        out=new Stack<>();
    }
    
    public void push(int x) {
        in.push(x);
    }
    
    public int pop() {
        popinout();
        return out.pop();

    }
    
    public int peek() {
        popinout();
        return out.peek();
    }
    
    public boolean empty() {
        if(in.isEmpty()&&out.isEmpty()){
            return true;
        }
        return false;
    }

    public void popinout(){
        if(out.isEmpty()){
            while (!in.isEmpty()) {
                out.push(in.pop());
            }
        }
    }
}

 

  •  在用栈实现队列时,对于队列来说,刚加入一个元素然后进行peek或者pop操作,被操作的那个数就是刚刚push进来的那个数

 

 225. 用队列实现栈

题目链接

class MyStack {
        Queue<Integer> que;

    public MyStack() {
        que=new LinkedList<>();

    }
    
    public void push(int x) {
        que.add(x);
        int size=que.size();
        while(size>1){
            que.add(que.poll());
            size--;
        }
    }
    
    public int pop() {
        return que.poll();
    }
    
    public int top() {
        return que.peek();
    }
    
    public boolean empty() {
        return que.isEmpty();
    }
}
  • 在加入元素到队列时就改变元素在队列中的顺序,模拟栈
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值