【Leetcode 232】 Implement Queue using Stacks - EASY

【Leetcode 232】 Implement Queue using Stacks - EASY

题目

Implement the following operations of a queue using stacks.

push(x) – Push element x to the back of queue.
pop() – Removes the element from in front of queue.
peek() – Get the front element.
empty() – Return whether the queue is empty.

用栈实现队列的以下方法:
push(x) – 将元素x加入队列
pop() – 取出队首元素
peek() – 返回队首元素
empty() – 判断队列中是否为空


Example:
MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false


Notes:
You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

思路

队列的特点是先进先出,而栈的特点是后进先出。

基于第225题【Leetcode 225】 Implement Stack using Queues - EASY的思路,我们也可以考虑用两个栈实现队列以及一个栈实现队列。

思路1

首先考虑用两个栈实现队列。
栈1用来存储数据,栈2用来倒置数据。
push(x):
将栈1中所有元素出栈,并且入栈2,然后将元素x入栈2,再将栈2中所有元素出栈并且入栈1。
pop() :
取出栈1的栈顶元素
peek() :
返回栈1的栈顶元素
empty() :
判断栈1是否为空

示例:
一个队列初始为空,依次执行:

queue.push(1);

在这里插入图片描述

queue.push(2);

在这里插入图片描述

queue.push(3);

在这里插入图片描述

queue.pop();

在这里插入图片描述

queue.peek();

在这里插入图片描述

queue.push(4);

在这里插入图片描述

题解

class MyQueue {

    private Stack<Integer> stack1;
    private Stack<Integer> stack2;
    
    
    /** Initialize your data structure here. */
    public MyQueue() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        while(!stack1.empty()){
            stack2.push(stack1.pop());
        }
        stack2.push(x);
        while(!stack2.empty()){
            stack1.push(stack2.pop());
        }
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        return stack1.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        return stack1.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stack1.empty();
    }
}

/**
 * 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();
 */

在这里插入图片描述

思路2

如果push操作较多,而pop操作较少,如何将push()的时间复杂度降至O(1)?
队列2用于添加元素,队列1用于出栈时进行倒置。
push(x):
将元素x入栈2
pop() :
将栈2中所有元素出栈并入栈1,然后弹出栈顶元素,再将剩下的元素出栈并入栈2
peek() :
用属性peek记录栈顶元素
empty() :
判断栈2是否为空

代码如下:

class MyQueue {

    private Stack<Integer> stack1;
    private Stack<Integer> stack2;
    private int peek;
    private int oldPeek;
    
    
    /** Initialize your data structure here. */
    public MyQueue() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        if(stack2.empty())
            peek = stack2.push(x);
        else
            stack2.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        while(!stack2.empty()){
            stack1.push(stack2.pop());
        }
        oldPeek = stack1.pop();
        if(!stack1.empty())
            peek = stack1.peek();
        while(!stack1.empty()){
            stack2.push(stack1.pop());
        }
        return oldPeek;
    }
    
    /** Get the front element. */
    public int peek() {
        return peek;
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stack2.empty();
    }
}

/**
 * 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();
 */

在这里插入图片描述

反思

复杂度分析

时间复杂度:

  • push(x):O(n)
  • pop():O(1)
  • peek():O(1)
  • empty():O(1)

思路反思

在前两种方法的基础上,或许可以有进一步的改进。
方法1——push–O(n) pop–O(1)
当有连续的push操作时,会造成浪费(多余的栈之间的迁徙操作
方法2——push–O(1) pop–O(n)
当有连续的pop操作时,会造成浪费(多余的栈之间的迁徙操作

所以可以在push和pop切换时,才进行栈之间的迁徙。
push(x):
如果栈1不为空,将栈1所有元素出栈并入栈2,然后将元素x入栈2
pop() :
如果栈2不为空,将栈2所有元素出栈并入栈1,然后弹出栈顶元素
peek() :
用属性peek记录栈顶元素
empty() :
判断栈1和栈2是否同时为空

代码如下:

class MyQueue {

    private Stack<Integer> stack1;
    private Stack<Integer> stack2;
    private int peek;
    private int oldPeek;
    
    
    /** Initialize your data structure here. */
    public MyQueue() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        while(!stack1.empty()){
            stack2.push(stack1.pop());
        }
        if(stack2.empty())
            peek = stack2.push(x);
        else
            stack2.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        while(!stack2.empty()){
            stack1.push(stack2.pop());
        }
        oldPeek = stack1.pop();
        if(!stack1.empty())
            peek = stack1.peek();
        return oldPeek;
    }
    
    /** Get the front element. */
    public int peek() {
        return peek;
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stack1.empty() && stack2.empty();
    }
}

/**
 * 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();
 */

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值