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 backpop from frontsize, and is empty operations 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 用队列来实现栈的更多相关文章

  1. LeetCode 225 Implement Stack using Queues 用队列实现栈

    1.两个队列实现,始终保持一个队列为空即可 class MyStack { public: /** Initialize your data structure here. */ MyStack() ...

  2. LeetCode 225 Implement Stack using Queues(用队列来实现栈)(*)

    翻译 用队列来实现栈的例如以下操作. push(x) -- 将元素x加入进栈 pop() -- 从栈顶移除元素 top() -- 返回栈顶元素 empty() -- 返回栈是否为空 注意: 你必须使用 ...

  3. [LeetCode] Implement Stack using Queues 用队列来实现栈

    Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...

  4. (easy)LeetCode 225.Implement Stack using Queues

    Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...

  5. 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 ...

  6. Leetcode 225 Implement Stack using Queues

    Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...

  7. Java [Leetcode 225]Implement Stack using Queues

    题目描述: Implement the following operations of a stack using queues. push(x) -- Push element x onto sta ...

  8. Leetcode 225 Implement Stack using Queues STL

    用两个队列去实现栈,这里我使用了队列数组q[2],在所有的过程中保证一个队列是空的 push时插入到空的队列中,然后将队列中的元素移到另一个队列中 pop时从不空的队列中pop() peek时从不空的 ...

  9. 225 Implement Stack using Queues(用队列实现栈Medium)

    题目意思:用队列实现栈,push(),pop(),top(),empty() 思路:用两个queue,pop时将一个queue的元素pop再push到另一个队列,queue只留最后一个元素,并pop, ...

随机推荐

  1. Python+Appium学习之启动手机APP或者浏览器

    一.启动浏览器:pycharm中python脚本如下: from appium import webdriver desired_caps ={ 'platformName':'Android', ' ...

  2. 51nod 1053 最大M子段和 V2

    N个整数组成的序列a[1],a[2],a[3],…,a[n],将这N个数划分为互不相交的M个子段,并且这M个子段的和是最大的.如果M >= N个数中正数的个数,那么输出所有正数的和. 例如:-2 ...

  3. CSP-S 2019提高组训练 服务器需求

    时间限制:C/C++ 3秒 空间限制:C/C++ 262144K 题目描述 小多计划在接下来的n天里租用一些服务器,所有的服务器都是相同的.接下来n天中,第i天需要\(a_i\)台服务器工作,每台服务 ...

  4. solr和ElasticSearch(ES)的区别?

    Solr2004年诞生 ElasticSearch 2010年诞生 ES更新 ElasticSearch简介: ElasticSearch是一个实时的分布式的搜索引擎和分析引擎.它可以帮助你用前所未有 ...

  5. MySql常用函数大全

    MySql常用函数大全 MySQL数据库中提供了很丰富的函数.MySQL函数包括数学函数.字符串函数.日期和时间函数.条件判断函数.系统信息函数.加密函数.格式化函数等.通过这些函数,可以简化用户的操 ...

  6. js 鼠标事件详细

    常用的几个类型 onClick HTML: 2 | 3 | 3.2 | 4 Browser: IE3 | N2 | O3 鼠标点击事件,多用在某个对象控制的范围内的鼠标点击 onDblClick HT ...

  7. 洛谷 P3388 【模板】割点(割顶)题解

    今天学了割点,就A了这道板子,比较难理解的地方就在于如果是根节点就要找两个点来满足low[y]>=dfn[x],如果不是就只需找一个点来满足.Tarjan(i,i)中第一个i是开始搜索的点而第 ...

  8. 洛谷 P2085 最小函数值

    目录 题目 思路 \(Code\) 题目 戳 思路 首先这些函数全部单带递增,因为\(a\),\(b\),\(c\)都是正整数. 我们将全部的函数的\(x\)为\(1\)时的函数值放入优先度列(小根堆 ...

  9. Go字符串常用处理

    应用到strings包 /** * @Author: jadeshu * @Description: * @File: main * @Version: 1.0.0 * @Date: 2019/11/ ...

  10. 【pytorch 代码】pytorch 网络结构可视化

    部分内容转载自 http://blog.csdn.net/GYGuo95/article/details/78821617,在此表示由衷感谢. 此方法需要安装python-graphviz:  con ...