Leetcode刷题日记-程序员面试经典(2020.6.23):化栈为队
题目描述:
思路整理:
此题为简单题,没啥说的,我们直接用两个栈,一个输入栈,一个输出栈即可来实现
代码:
#!/usr/bin/env python # -*- coding: utf-8 -*- """ # @Time : 2020/6/24 9:20 # @Author : ZFJ # @File : 化栈为队.py # @Software: PyCharm """ class MyQueue(object): """ 方法还是很简单,我们使用两个列表来模型入栈和出栈即可 """ def __init__(self): """ Initialize your data structure here. """ # 定义输入栈和输出栈 self.pushs = [] self.pops = [] def push(self, x): """ Push element x to the back of queue. :type x: int :rtype: None """ # 实现入队列 self.pushs.append(x) def pop(self): """ Removes the element from in front of queue and returns that element. :rtype: int """ # 输出队列 # 遇到现在输出栈为空 if len(self.pops) == 0: # 将输入栈元素添加到输出栈 for i in range(len(self.pushs)): # 调用pop()操作即可将先进后出转换成先进先出 self.pops.append(self.pushs.pop()) return self.pops.pop() def peek(self): """ Get the front element. :rtype: int """ # 现在输出栈为空 if len(self.pops) == 0: for i in range(len(self.pushs)): self.pops.append(self.pushs.pop()) # 因为peek()操作只是查看元素,不会移除元素,因此还要再次添加到栈中 temp = self.pops.pop() self.pops.append(temp) return temp def empty(self): """ Returns whether the queue is empty. :rtype: bool """ # 只有输入栈和输出栈都为空,才能判断队列为空 if len(self.pushs) == 0 and len(self.pops) == 0: return True else: return False # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(1) # obj.push(2) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty()