代码随想录算法训练营第十天|232.用栈实现队列 ,225. 用队列实现栈

232. Implement Queue using Stacks

225. Implement Stack using Queues

今天这俩差不多,主要是看对STACK的FILO和QUEUE的FIFO的理解,做法也差不多,就合在一起写了

无论是232 还是 225都可以用 一个STACK/QUEUE的思想来解决,就是在push里利用该数据结构的特性整理一下,满足之后pop以及peek的需求

232 由于要implement的是FIFO的 QUEUE,所以在每次push的时候,把stack里的数据全push到一个临时stack中,最后把新加进来的数push进去,然后再把temp的数全push到原stack中,这样stack刚好是倒序,可以直接pop peek符合queue的情况

225也是类似,由于implement FILO的stack,也就是说新加进来的数要整理后放在queue的首位,于是每次push之后,把新加进去的数之前的数全queue.add(queue.remove())到后面即可,由于QUEUE的特性

//232. Implement Queue using Stacks

Stack<Integer> stack;

    public MyQueue() {
        stack = new Stack<>();
    }
    
    public void push(int x) {
        Stack<Integer> temp = new Stack<>();
        while(!stack.isEmpty()){
            temp.push(stack.pop());
        }
        temp.push(x);
        while(!temp.isEmpty()){
            stack.push(temp.pop());
        }
    }
    
    public int pop() {
        return stack.pop();
    }
    
    public int peek() {
        return stack.peek();
    }
    
    public boolean empty() {
        return stack.isEmpty() ? true : false;
    }
}






// 225. Implement Stack using Queues
class MyStack {
    Queue<Integer> queue;

    public MyStack() {
        queue = new LinkedList<>();
    }
    
    public void push(int x) {
        queue.add(x);
        for(int i = 0; i< queue.size() -1 ; i++ ){
            queue.add(queue.remove());
        }
        
    }
    
    public int pop() {
        return queue.poll();
    }
    
    public int top() {
        return queue.peek();
    }
    
    public boolean empty() {
        return  queue.isEmpty() ? true: false;  
    }
}

,这里不需要申请临时queue

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值