[LeetCode] 225. Implement Stack using Queues 用队列来实现栈
Implement the following operations of a stack using queues.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- empty() -- Return whether the stack is empty.
Notes:
- You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
- Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue -- which means only
push to back,pop from front,size, andis emptyoperations are valid.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and all test cases.
用队列Queues的基本操作来实现栈Stack,队列和栈都是重要的数据结构,区别主要是,队列是先进先出,而栈是先进后出。
解法1: 在队列push进来新元素时,就把其它元素pop出来排到新元素的后面,新元素就在前面了,就可以后进先出。就好像大家都在排队,来了个重要客人,要让他第一,其他人从前面按顺序跑到他后面。
解法2: push的时候,其他元素不动只是用一个变量记住这个新元素。当top的时候直接给这个变量的值。当pop时,在调整顺序,把最后一个排到前面,弹出。变量记住目前在最尾部的值。
Java:
class MyStack {
LinkedList<Integer> queue1 = new LinkedList<Integer>();
LinkedList<Integer> queue2 = new LinkedList<Integer>();
// Push element x onto stack.
public void push(int x) {
if(empty()){
queue1.offer(x);
}else{
if(queue1.size()>0){
queue2.offer(x);
int size = queue1.size();
while(size>0){
queue2.offer(queue1.poll());
size--;
}
}else if(queue2.size()>0){
queue1.offer(x);
int size = queue2.size();
while(size>0){
queue1.offer(queue2.poll());
size--;
}
}
}
}
// Removes the element on top of the stack.
public void pop() {
if(queue1.size()>0){
queue1.poll();
}else if(queue2.size()>0){
queue2.poll();
}
}
// Get the top element.
public int top() {
if(queue1.size()>0){
return queue1.peek();
}else if(queue2.size()>0){
return queue2.peek();
}
return 0;
}
// Return whether the stack is empty.
public boolean empty() {
return queue1.isEmpty() & queue2.isEmpty();
}
}
Python: Time: push: O(n), pop: O(1), top: O(1), Space: O(n)
class Queue:
def __init__(self):
self.data = collections.deque() def push(self, x):
self.data.append(x) def peek(self):
return self.data[0] def pop(self):
return self.data.popleft() def size(self):
return len(self.data) def empty(self):
return len(self.data) == 0 class Stack:
# initialize your data structure here.
def __init__(self):
self.q_ = Queue() # @param x, an integer
# @return nothing
def push(self, x):
self.q_.push(x)
for _ in xrange(self.q_.size() - 1):
self.q_.push(self.q_.pop()) # @return nothing
def pop(self):
self.q_.pop() # @return an integer
def top(self):
return self.q_.peek() # @return an boolean
def empty(self):
return self.q_.empty()
Python: Time: push: O(1), pop: O(n), top: O(1),Space: O(n)
class Stack:
# initialize your data structure here.
def __init__(self):
self.q_ = Queue()
self.top_ = None # @param x, an integer
# @return nothing
def push(self, x):
self.q_.push(x)
self.top_ = x # @return nothing
def pop(self):
for _ in xrange(self.q_.size() - 1):
self.top_ = self.q_.pop()
self.q_.push(self.top_)
self.q_.pop() # @return an integer
def top(self):
return self.top_ # @return an boolean
def empty(self):
return self.q_.empty()
类似题目:
[LeetCode] 232. Implement Queue using Stacks 用栈来实现队列
All LeetCode Questions List 题目汇总
[LeetCode] 225. Implement Stack using Queues 用队列来实现栈的更多相关文章
- LeetCode 225 Implement Stack using Queues 用队列实现栈
1.两个队列实现,始终保持一个队列为空即可 class MyStack { public: /** Initialize your data structure here. */ MyStack() ...
- LeetCode 225 Implement Stack using Queues(用队列来实现栈)(*)
翻译 用队列来实现栈的例如以下操作. push(x) -- 将元素x加入进栈 pop() -- 从栈顶移除元素 top() -- 返回栈顶元素 empty() -- 返回栈是否为空 注意: 你必须使用 ...
- [LeetCode] Implement Stack using Queues 用队列来实现栈
Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...
- (easy)LeetCode 225.Implement Stack using Queues
Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...
- Java for LeetCode 225 Implement Stack using Queues
Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...
- Leetcode 225 Implement Stack using Queues
Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...
- Java [Leetcode 225]Implement Stack using Queues
题目描述: Implement the following operations of a stack using queues. push(x) -- Push element x onto sta ...
- Leetcode 225 Implement Stack using Queues STL
用两个队列去实现栈,这里我使用了队列数组q[2],在所有的过程中保证一个队列是空的 push时插入到空的队列中,然后将队列中的元素移到另一个队列中 pop时从不空的队列中pop() peek时从不空的 ...
- 225 Implement Stack using Queues(用队列实现栈Medium)
题目意思:用队列实现栈,push(),pop(),top(),empty() 思路:用两个queue,pop时将一个queue的元素pop再push到另一个队列,queue只留最后一个元素,并pop, ...
随机推荐
- Python练习题——用列表的方法输出杨辉三角
def main(): num = int(input('请输入行数: ')) yh = [[]] * num #创建num行空列表 for row in range(len(yh)): #遍历每一行 ...
- FFT版题 [51 Nod 1028] 大数乘法
题目链接:51 Nod 传送门 数的长度为10510^5105,乘起来后最大长度为2×1052\times10^52×105 由于FFT需要把长度开到222的次幂,所以不能只开到2×1052\time ...
- 指数基金介绍专栏(4):上证50AH优选指数
作者:牛大 | 公众号:定投五分钟 大家好,我是牛大.每天五分钟,投资你自己:坚持基金定投,终会财富自由! 想必大家会有疑问,什么是上证50AH优选指数?今天老师给大家答疑解惑,详细介绍一下上证50A ...
- 创建nextcloud所需的数据库和账户
创建 nextcloud 所需的数据库和账户 打开数据库管理命令行,默认root没密码,回车进入 sudo mysql -u root -p 创建 nextcloud 数据库,命令包含后面的分号 ...
- S1_搭建分布式OpenStack集群_10 cinder 存储节点配置
一.安装配置lvm2安装LVM包:# yum install -y lvm2 启动LVM元数据服务,并将其配置为在系统启动时启动:# systemctl enable lvm2-lvmetad.ser ...
- SOS.DLL在windbg里加载错误
sos.dll/mscordacwks.dll 公共语言运行库(CLR)是执行托管代码的Microsoft.NET框架的核心引擎.简单地说,它通过在托管程序集中使用中间语言和元数据,JIT按需编译代码 ...
- High scalability with Fanout and Fastly
转自:http://blog.fanout.io/2017/11/15/high-scalability-fanout-fastly/ Fanout Cloud is for high scale d ...
- Python TIPS上一道关于人民币金额小写转大写的题
人民币金额打印 题目链接:here.我发现我写的好复杂,但万幸编码还算符合人类,看了其他答案,感觉都是天书. #!/usr/bin/env python # -*- coding: utf-8 -*- ...
- Linux进阶之Shell编程
1.什么是Shell Shell是一个命名行解释器,它为用户提供一个向Linux内核发送请求以便运行程序的界面系统级程序,用户可以用Shell来启动.挂起.停止甚至是编写一些程序. 2.Shell脚本 ...
- 刷题记录:[DDCTF 2019]homebrew event loop
目录 刷题记录:[DDCTF 2019]homebrew event loop 知识点 1.逻辑漏洞 2.flask session解密 总结 刷题记录:[DDCTF 2019]homebrew ev ...