问题描述:
使用栈实现队列的下列操作:
- push(x) -- 将一个元素放入队列的尾部。
- pop() -- 从队列首部移除元素。
- peek() -- 返回队列首部的元素。
- empty() -- 返回队列是否为空。
示例:
MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false
说明:
- 你只能使用标准的栈操作 -- 也就是只有
push to top
,peek/pop from top
,size
, 和is empty
操作是合法的。 - 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
- 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
方法:
1 class MyQueue(object): 2 3 def __init__(self): 4 """ 5 Initialize your data structure here. 6 """ 7 self.lists = [] 8 9 def push(self, x): 10 """ 11 Push element x to the back of queue. 12 :type x: int 13 :rtype: void 14 """ 15 self.lists.append(x) 16 17 def pop(self): 18 """ 19 Removes the element from in front of queue and returns that element. 20 :rtype: int 21 """ 22 return self.lists.pop(0) 23 24 def peek(self): 25 """ 26 Get the front element. 27 :rtype: int 28 """ 29 return self.lists[0] 30 31 32 def empty(self): 33 """ 34 Returns whether the queue is empty. 35 :rtype: bool 36 """ 37 return len(self.lists) == 0
官方:
1 闭 2 执行用时为 20 ms 的范例 3 class MyQueue(object): 4 5 def __init__(self): 6 """ 7 Initialize your data structure here. 8 """ 9 self.instack=[] 10 self.outstack=[] 11 12 13 def push(self, x): 14 """ 15 Push element x to the back of queue. 16 :type x: int 17 :rtype: void 18 """ 19 self.instack.append(x) 20 21 def pop(self): 22 """ 23 Removes the element from in front of queue and returns that element. 24 :rtype: int 25 """ 26 if self.outstack==[]: 27 while self.instack!=[]: 28 self.outstack.append(self.instack.pop()) 29 return self.outstack.pop() 30 31 32 def peek(self): 33 """ 34 Get the front element. 35 :rtype: int 36 """ 37 if self.outstack==[]: 38 while self.instack!=[]: 39 self.outstack.append(self.instack.pop()) 40 return self.outstack[-1] 41 42 def empty(self): 43 """ 44 Returns whether the queue is empty. 45 :rtype: bool 46 """ 47 return self.instack==[] and self.outstack==[]
2018-09-20 13:35:00