侧重点
- 掌握队列的构造方式(利用栈的特点进行构造)
- 掌握栈自带的方法运用:
a. pop()
b. append()
c. stack[-1]表示栈顶元素
题目
1. 用两个栈实现队列
题解:
class CQueue(object):
def __init__(self):
self.stack1=[]
self.stack2=[] #用与删除头部队列使用
#队列尾部插入整数
#插入操作不需要返回值
def appendTail(self, value):
"""
:type value: int
:rtype: None
"""
self.stack1.append(value)
#返回队列头部删除的整数
def deleteHead(self):
"""
:rtype: int
"""
if self.stack2:
return self.stack2.pop()
if not self.stack1:
return -1
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
# Your CQueue object will be instantiated and called as such:
# obj = CQueue()
# obj.appendTail(value)
# param_2 = obj.deleteHead()
2. 包含min函数的栈
题解:
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack1=[]
self.stack2=[] #删除
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.stack1.append(x)
if not self.stack2 or self.stack2[-1]>=x: #注意相同时也需要入栈!!!
self.stack2.append(x)
def pop(self):
"""
:rtype: None
"""
if self.stack2[-1]==self.stack1.pop():
self.stack2.pop()
def top(self):
"""
:rtype: int
"""
return self.stack1[-1]
def min(self):
"""
:rtype: int
"""
return self.stack2[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.min()