两个栈实现队列 Python实现
# coding=utf-8 MAX_LENGTH = 100 SUCCESS = 1 FAIL = 0 ERROR = -1 class Queue(object): stack_fir = None stack_sec = None queue_len = 0 def __init__(self): self.stack_fir = Stack() self.stack_sec = Stack() self.queue_len = 0 # 队列push方法 def push(self, item): if self.queue_len == MAX_LENGTH: return Result(FAIL, None) elif self.queue_len > MAX_LENGTH: return Result(ERROR, None) self.queue_len += 1 result = self.stack_fir.push(item) if result.get_code() == SUCCESS: return Result(SUCCESS, None) else: return Result(FAIL, None) # 队列pop方法 def pop(self): if self.queue_len == 0: return Result(FAIL, None) elif self.queue_len < 0: return Result(ERROR, None) self.queue_len -= 1 # 将装有数据的栈拷贝到空栈中 while self.stack_fir.has_next(): pop_result = self.stack_fir.pop() if pop_result.get_code() == SUCCESS: self.stack_sec.push(pop_result.get_value()) result = self.stack_sec.pop().get_value() # 将装有数据的栈拷贝到空栈中 while self.stack_sec.has_next(): pop_result = self.stack_sec.pop() if pop_result.get_code() == SUCCESS: self.stack_fir.push(pop_result.get_value()) return Result(SUCCESS, result) # 队列是否有下一个元素 def has_next(self): return self.queue_len > 0 class Stack(object): stack_len = 0 item_list = [] def __init__(self): self.stack_len = 0 self.item_list = [] # 栈push方法 def push(self, item): if self.stack_len == MAX_LENGTH: return Result(FAIL, None) elif self.stack_len > MAX_LENGTH: return Result(ERROR, None) self.stack_len += 1 self.item_list.append(item) return Result(SUCCESS, None) # 栈pop方法 def pop(self): if self.stack_len == 0: return Result(FAIL, None) elif self.stack_len < 0: return Result(ERROR, None) self.stack_len -= 1 item = self.item_list[self.stack_len] del self.item_list[self.stack_len] return Result(SUCCESS, item) # 栈是否有下一个元素 def has_next(self): return self.stack_len > 0 class Result(object): code = 0 value = None def __init__(self, code, value): self.code = code self.value = value def get_code(self): return self.code def get_value(self): return self.value if __name__ == '__main__': queue = Queue() queue.push(1) queue.push(2) queue.push(5) queue.push(4) queue.push(3) while queue.has_next(): print queue.pop().get_value()