题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。 python实现:
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, node):
# write code here
self.stack.append(node)
if len(self.min_stack)>0: # 空栈
node = min(node, self.min_stack[-1]) # 与栈顶比较
self.min_stack.append(node)
def pop(self):
# write code here
if len(self.stack)>0:
self.min_stack.pop()
return self.stack.pop()
else: # 空栈
raise Exception("Error: empty stack!")
def top(self):
# write code here
if len(self.stack)>0:
return self.stack[-1]
else:
raise Exception("Error: empty stack!")
def min(self):
# write code here
if len(self.min_stack)>0:
return self.min_stack[-1]
else:
raise Exception("Error: empty stack!")
c++实现:
class Solution {
private:
vector<int> stack;
vector<int> minStack;
public:
void push(int value) {
stack.push_back(value);
if(!minStack.empty()){
int top = minStack.back();
value = std::min(top, value);
}
minStack.push_back(value);
}
void pop() {
if(!stack.empty()){
stack.pop_back();
minStack.pop_back();
}
}
int top() {
if(!stack.empty()){
return stack.back();
}
return NULL;
}
int min() {
if(!minStack.empty()){
return minStack.back();
}
return NULL;
}
};