以查找最小值为例
class MyStack:
def __init__(self):
self.values = []
self.mins = []
def push(self, ins):
if not self.mins:
self.mins.append((0, ins))
elif ins < self.mins[-1][1]:
self.mins.append(
(len(self.values), ins)
)
self.values.append(ins)
def pop(self):
if self.mins and len(self.values)-1 == self.mins[-1][0]:
self.mins.pop()
return self.values.pop() if self.values else None
# def top(self):
# return self.values[-1] if self.values else None
def get_min(self):
return self.mins[-1][1] if self.mins else None