232.用棧實現隊列
使用棧實現隊列的下列操作:
- 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 操作)。
解法一:
想了一下其實python裏的隊列就相當於一個棧,而且list可以直接pop並且是pop指定位並且調整List,所以用list非常方便的就實現了。
class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.list = []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: None
"""
self.list.append(x)
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
return self.list.pop(0)
def peek(self):
"""
Get the front element.
:rtype: int
"""
return self.list[0]
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
if len(self.list) == 0:
return True
else:
return False
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()