225. 用队列实现栈
2022/1/24 23:08:29
本文主要是介绍225. 用队列实现栈,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
225. 用队列实现栈
难度 简单
题目描述
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。 int pop() 移除并返回栈顶元素。 int top() 返回栈顶元素。 boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
注意:
你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
示例:
输入: ["MyStack", "push", "push", "top", "pop", "empty"] [[], [1], [2], [], [], []] 输出: [null, null, null, 2, 2, false]
解题:
用两个队列来完成
首先其pop,top,empty很好完成
其次,对于push,可以简单的用一个额外的空队列进行中转,完成操作
class MyStack: def __init__(self): """ Initialize your data structure here. """ self.queue1 = collections.deque() self.queue2 = collections.deque() def push(self, x: int) -> None: """ Push element x onto stack. """ self.queue2.append(x) while self.queue1: self.queue2.append(self.queue1.popleft()) self.queue1, self.queue2 = self.queue2, self.queue1 def pop(self) -> int: """ Removes the element on top of the stack and returns that element. """ return self.queue1.popleft() def top(self) -> int: """ Get the top element. """ return self.queue1[0] def empty(self) -> bool: """ Returns whether the stack is empty. """ return not self.queue1
这篇关于225. 用队列实现栈的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)