代码随想录算法训练营第十天|栈与队列|理论基础|232.用栈实现队列|225. 用队列实现栈

文章介绍了如何利用栈和队列这两种基本数据结构来实现其他操作,如用栈实现队列的push、pop、peek和empty方法,以及用队列实现栈的push、pop、top和empty操作。这些实现基于对栈后进先出(LIFO)和队列先进先出(FIFO)性质的理解和巧妙利用。
摘要由CSDN通过智能技术生成

232.用栈实现队列

题解及想法

 

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() {
            dumpstackIn();
            return stack2.pop();
        }

        public int peek() {
            dumpstackIn();
            return stack2.peek();
        }

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

        private void dumpstackIn(){
            if(!stack2.isEmpty()){
                return;
            }
            while (!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
        }
}

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

225. 用队列实现栈

题解及想法

 

 class MyStack {

        Queue<Integer> queue1;

        public MyStack() {
            queue1 = new LinkedList<>();
        }

        public void push(int x) {
            queue1.offer(x);
            int size = queue1.size();
            size--;
            while (size-- > 0){
                queue1.offer(queue1.poll());
            }
        }

        public int pop() {
            return queue1.poll();
        }

        public int top() {
            return queue1.peek();
        }

        public boolean empty() {
            return queue1.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();
 */
返回该题
力扣 LeetCode

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值