两个栈实现队列
2018-04-25 本文已影响9人
只为此心无垠
核心是adjust方法:
每次pop或top就是更新时间,更新前提是辅助栈为空
def __init__(self):
# do intialization if necessary
self.stack_main = []
self.stack_help = []
"""
@param: element: An integer
@return: nothing
"""
def push(self, element):
# write your code here
self.stack_main.append(element)
"""
@return: An integer
"""
def adjust(self):
if len(self.stack_help) == 0:
while len(self.stack_main) != 0:
self.stack_help.append(self.stack_main.pop(-1))
def pop(self):
# write your code here
self.adjust()
n = len(self.stack_help)
if n == 0:
return None
return self.stack_help.pop(-1)
"""
@return: An integer
"""
def top(self):
# write your code here
self.adjust()
n = len(self.stack_help)
if n == 0:
return None
return self.stack_help[-1]