面试题9:用两个栈实现队列(leetcode 232)
由于leetcode上面的232题(用栈实现队列)实现了队列更多的功能,因此以232题为例。
题目描述:使用栈实现队列的下列操作:
- push(x) – 将一个元素放入队列的尾部。
- pop() – 从队列首部移除元素。
- peek() – 返回队列首部的元素。
- empty() – 返回队列是否为空。
详细代码:
class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack_A = []
self.stack_B = []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: None
"""
self.stack_A.append(x)
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
if self.stack_B:
return self.stack_B.pop()
elif not self.stack_A:
return None
else:
while self.stack_A:
self.stack_B.append(self.stack_A.pop())
return self.stack_B.pop()
def peek(self):
"""
Get the front element.
:rtype: int
"""
if self.stack_B:
front = self.stack_B.pop()
self.stack_B.append(front)
return front
elif not self.stack_A:
return None
else:
while self.stack_A:
self.stack_B.append(self.stack_A.pop())
front = self.stack_B.pop()
self.stack_B.append(front)
return front
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
if not self.stack_A and not self.stack_B:
return True
else:
return False
相关题目:用两个队列实现栈(leetcode 225)
由于leetcode上面的225题(用队列实现栈)实现了栈更多的功能,因此以225题为例。
题目描述:使用队列实现栈的下列操作:
- push(x) – 元素 x 入栈
- pop() – 移除栈顶元素
- top() – 获取栈顶元素
- empty() – 返回栈是否为空
详细代码:
class MyStack(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.q1 = []
self.q2 = []
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: None
"""
self.q1.insert(0, x)
def pop(self):
"""
Removes the element on top of the stack and returns that element.
:rtype: int
"""
if not self.q1 and not self.q2:
return None
elif self.q1:
return self.q1.pop(0)
else:
while len(self.q2) != 1:
self.q1.insert(0, self.q2.pop())
return self.q2.pop()
def top(self):
"""
Get the top element.
:rtype: int
"""
if not self.q1 and not self.q2:
return None
elif self.q1:
front = self.q1.pop(0)
self.q1.insert(0, front)
return front
else:
while len(self.q2) != 1:
self.q1.insert(0, self.q2.pop())
front = self.q2.pop()
self.q1.insert(0, front)
return front
def empty(self):
"""
Returns whether the stack is empty.
:rtype: bool
"""
if not self.q1 and not self.q2:
return True
else:
return False