首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leecode刷题(26)-- 用栈实现队列

leecode刷题(26)-- 用栈实现队列

作者头像
希希里之海
发布2019-05-14 15:26:47
3010
发布2019-05-14 15:26:47
举报
文章被收录于专栏:weixuqin 的专栏weixuqin 的专栏

leecode刷题(26)-- 用栈实现队列

用栈实现队列

使用栈实现队列的下列操作:

  • push(x) -- 将一个元素放入队列的尾部。
  • pop() -- 从队列首部移除元素。
  • peek() -- 返回队列首部的元素。
  • empty() -- 返回队列是否为空。

示例:

MyQueue queue = new MyQueue();

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

说明:

  • 你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
  • 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
  • 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。

思路

首先了解下栈和队列的特点:

  • 栈:后进先出
  • 队列:先进后出

所以我们只用一个栈的话是无法实现队列的操作的。不妨换个思路,我们用两个栈来实现队列:

当栈2不为空时直接 pop,否则把栈1的所有元素放到栈2然后执行栈2 pop 操作。

思路.png
思路.png

代码如下:

java描述

import java.util.Stack;

class MyQueue {

    /** Initialize your data structure here. */
        Stack<Integer> s1 = new Stack<Integer>();
        Stack<Integer> s2 = new Stack<Integer>();
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        s1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if (!s2.isEmpty())  return s2.pop();
        while (!s1.isEmpty()) {
            int val = s1.pop();
            s2.push(val);
        }
        return s2.pop();
    }

    
    /** Get the front element. */
    public int peek() {
        if (!s2.isEmpty())  return s2.peek();
        while (!s1.isEmpty()) {
            int val = s1.pop();
            s2.push(val);
        }
        return s2.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return s1.empty() && s2.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();
 */

python3描述

from collections import deque

class Stack:
    def __init__(self):
        self.items = deque()
    
    def push(self, val):
        return self.items.append(val)
    
    def pop(self):
        return self.items.pop()

    def top(self):
        return self.items[-1]

    def empty(self):
        return len(self.items) == 0

class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.s1 = Stack()
        self.s2 = Stack()

    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.s1.push(x)

    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        if not self.s2.empty():
            return self.s2.pop()
        while not self.s1.empty():
            val = self.s1.pop()
            self.s2.push(val)
        return self.s2.pop()

    def peek(self) -> int:
        """
        Get the front element.
        """
        if not self.s2.empty():
            return self.s2.top()
        while not self.s1.empty():
            val = self.s1.pop()
            self.s2.push(val)
        return self.s2.top()

    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        return self.s1.empty() and self.s2.empty()


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

总结

可以看出,java支持栈,我们可以直接调用java.util.Stack ,而 python 不支持栈,我们可以自己使用 deque(双端队列),来模拟一个栈。时间和内存对比如下:

对比.png
对比.png
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-05-05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • leecode刷题(26)-- 用栈实现队列
    • 用栈实现队列
      • 思路
        • 代码如下:
          • 总结
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档