代码块
例如:
#coding=utf-8
class Stack(object):
def __init__(self):
self.__items = []
def is_empty(self):
return self.__items == []
def peek(self):
return self.__items[-1]
def pop(self):
return self.__items.pop()
def size(self):
return len(self.__items)
def push(self, item):
self.__items.append(item)
class MinStack(object):
def __init__(self):
self.data_stack = Stack()
self.min_stack = Stack()
def pop(self):
if not self.data_stack.is_empty():
result = self.data_stack.pop()
if result == self.min_stack.peek():
self.min_stack.pop()
return result
else:
return -1
def peek(self):
return self.data_stack.peek()
def push(self, item):
self.data_stack.push(item)
if self.min_stack.is_empty() or item <= self.min_stack.peek():
self.min_stack.push(item)
def get_min(self):
if not self.min_stack.is_empty():
return self.min_stack.peek()
else:
return -1
def test1():
min_stack = MinStack()
min_stack.push(3)
min_stack.push(4)
min_stack.push(5)
min_stack.push(1)
min_stack.push(3)
min_stack.push(1)
min_stack.push(2)
print min_stack.get_min()
min_stack.pop()
min_stack.pop()
min_stack.pop()
min_stack.pop()
print min_stack.get_min()
def main():
test1()
if __name__ == '__main__':
main()
//使用数组模拟两个栈 一个放所有数据一个存放最小数据
var data_stack = [];
var min_stack = [];
//栈的push
function spush(val){
data_stack.push(val);
if(min_stack.length == 0){
min_stack.push(val)
}
else if(data_stack[data_stack.length-1] <= min_stack[min_stack.length -1]){
min_stack.push(val)
}
}
//栈的pop
function spop(){
var res = data_stack.pop()
if(res == min_stack[min_stack.length-1]){
min_stack.pop()
}
}
//获取最小值
function getMin(){
if(min_stack.length !=0){
return min_stack[min_stack.length-1]
}
}
function test(){
spush(3)
spush(4)
spush(2)
spush(1)
spush(2)
spop()
spop()
}
test();
console.log(getMin())