用python实现有getMin()功能的栈

算法1.用python实现有getMin()功能的栈

class Stack:
def init(self):
self.item = []

def push(self, item):
    self.item.append(item)

def pop(self):
    if len(self.item) == 0:
        return "your stack is empty"
    else:
        self.item.pop()

def peek(self):
    return self.item[len(self.item) - 1]
def all(self):
    return self.item[:]

class MyStack1(Stack):
def init(self):
self.stackData = Stack()
self.stackMin = Stack()

def push(self, num):
    if len(self.stackMin.item) == 0:
        self.stackMin.push(num)
    elif num <= self.getmin():
        self.stackMin.push(num)

    self.stackData.push(num)

def pop(self):
    if len(self.stackData.item) == 0:
        return "the stackdata is empty"
    value=self.stackData.item.pop()
    if ( value == self.getmin()):
        self.stackMin.item.pop()





def getmin(self):
    if len(self.stackMin.item) == 0:
        return "the stackmin is empty"
    return self.stackMin.peek()

s = MyStack1()
s.push(3)
s.push(4)
s.push(5)
s.push(1)
s.push(2)
s.push(1)
print(‘stackdata栈中所有元素:’,s.stackData.all())
print(‘stackdata的栈顶’,s.stackData.peek())
print(‘stackmin栈中所有元素:’,s.stackMin.all())
print(‘stackmin的栈顶’,s.stackMin.peek())
print(‘min’,s.getmin())
s.pop()
s.pop()
s.pop()
#s.push(1)
print(‘stackdata栈中所有元素:’,s.stackData.all())
print(‘stackdata的栈顶’,s.stackData.peek())
print(‘stackmin栈中所有元素:’,s.stackMin.all())
print(‘stackmin的栈顶’,s.stackMin.peek())
print(‘min’,s.getmin())

你可能感兴趣的:(面试算法)