您的位置:首页 > Web前端

剑指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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: