剑指offer 07 用两个栈实现队列
2017-08-03 20:23
190 查看
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。思路:
入队:先放进一个栈中,再把栈的元素放入另一个栈,最后再放回。
出队:直接出栈。
class stack:
def __init__(self):
self.index = 0
self.content = []
def push(self, x):
self.index += 1
if len(self.content) < self.index:
self.content.append(x)
else:
self.content[self.index - 1] = x
def pop(self):
if self.index > 0:
self.index -= 1
return self.content[self.index]
def empty(self):
if self.index == 0:
return 1
return 0
class Solution:
def __init__(self):
self.datastack = stack()
self.tmpstack = stack()
def push(self, node):
if self.datastack.empty():
self.datastack.push(node)
else:
while not self.datastack.empty():
self.tmpstack.push(self.datastack.pop())
self.tmpstack.push(node)
while not self.tmpstack.empty():
self.datastack.push(self.tmpstack.pop())
def pop(self):
return self.datastack.pop()
相关文章推荐
- 面试题07_用两个栈实现队列——剑指offer系列
- 剑指offer :07 用两个栈实现队列
- 面试题07_用两个栈实现队列——剑指offer系列
- 《剑指offer》面试题7:用两个栈实现队列
- 剑指offer面试题7(java实现):用两个栈实现队列
- 《剑指offer》用两个栈实现队列
- 剑指offer(五,六),用两个栈实现队列,旋转数组的最小数字
- 【剑指offer-Java版】07用两个栈实现队列
- [剑指offer][面试题07]用两个栈实现队列
- 剑指offer 面试题7 两个栈实现队列 java版答案
- 剑指Offer系列---(9)用两个栈实现队列和用两个队列实现栈
- 【剑指offer】面试题07:用两个栈实现队列
- 剑指offer《面试题7:用两个栈实现队列》及用两个队列实现一个栈
- 剑指offer第五题两个栈实现队列功能
- 《剑指offer》用两个栈实现队列
- 剑指offer_用两个栈实现队列
- 《剑指Offer》面试题7:用两个栈实现队列
- 剑指Offer学习之面试题7:用两个栈实现队列
- 剑指offer面试题7:用两个栈实现队列
- 剑指offer 用两个栈实现队列