admin管理员组文章数量:1636963
题目链接
https://leetcode/problems/implement-queue-using-stacks/
题目原文
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.
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).
题目翻译
太长不翻了。大概就是用栈的push to top, peek/pop from top, size, is empty方法,实现队列的push, pop, peek, empty方法。
思路方法
镜像问题:225. Implement Stack using Queues
这个题目的关键点在于,只能用栈的几个操作实现。
由于栈先进后出,和队列先进先出天然矛盾,故考虑采用两个栈,一个只进行入栈push操作,一个只进行出栈pop或peek操作。当只进行出栈操作的栈空时将另一个栈中的内容push到该栈,如此,就拥有了先进先出的特性。
代码
class Queue(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.inStack, self.outStack = [], []
def push(self, x):
"""
:type x: int
:rtype: nothing
"""
self.inStack.append(x)
def pop(self):
"""
:rtype: nothing
"""
self.peek()
self.outStack.pop()
def peek(self):
"""
:rtype: int
"""
if not self.outStack:
while self.inStack:
self.outStack.append(self.inStack.pop())
return self.outStack[-1]
def empty(self):
"""
:rtype: bool
"""
return not self.inStack and not self.outStack
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn/coder_orz/article/details/51586814
本文标签: QueueimplementPythonEasyStacks
版权声明:本文标题:232. Implement Queue using Stacks [easy] (Python) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/xitong/1729235274a1191920.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论