最小栈的操作和普通栈的操作没有太大区别,唯一多了一个方法就是getMin()方法,这个方法是用来获取当前栈内的最小值。
直接上代码:
第一种:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<iostream>
#include<stack>
using namespace std;
class min_stack
{
public:
void Push(int value)
{
if (s1.empty())//第一个元素进栈
{
s1.push(value);//s1为正常栈
s2.push(value);//s2为存放正常栈的最小值
}
else
{
if (value > s2.top())//如果当前值大于最小值
{
s1.push(value);//只进s1
}
else//小于或等于
{
s1.push(value);
s2.push(value);
}
}
}
void Pop()
{
if (s1.empty())
{
printf("栈为空\n");
return;
}
if (s1.top() > s2.top())//如果s1的栈顶元素不是最小值
{
s1.pop();
}
else if (s1.top() == s2.top())//相等的话,两个都出栈
{
s1.pop();
s2.pop();
}
}
int GetMin()
{
return s2.top();//s2栈顶为当前栈元素内的最小值
}
int GetTop()
{
return s1.top();//返回正常栈栈顶
}
void Print()
{
if (s1.empty())
{
printf("栈为空\n");
return ;
}
while (s1.size())
{
cout <<"| "<< s1.top()<<" |" << endl;
s1.pop();
}
cout << "栈的最小元素为" << s2.top() << endl;
}
private:
stack <int> s1, s2;
};
int main()
{
min_stack s1;
s1.Push(1);
s1.Push(3);
s1.Push(-2);
s1.Push(4);
s1.Push(2);
s1.Push(-3);
s1.Pop();
s1.GetMin();
s1.GetTop();
s1.Print();
system("pause");
return 0;
}
运行结果:
第二种:(用容器实现)
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <vector>
using namespace std;
class MinStack {
public:
vector<int> stack;
int min;
void push(int x) {
if (stack.empty()) //如果为空,直接入栈
{
stack.push_back(0);
min = x;//设置min值为x
}
else//不为空
{
stack.push_back(x - min);//把值变为 x-min再入栈 切记!!!
if (x < min) //如果要入栈得x小于当前min值
{
min = x;//更新min值
}
}
}
void pop() {
if (stack.empty()) {
return;
}
else{
if (stack.back() < 0) //因为back是通过当前元素x-min值得到的,所以back为负数说明这时候得入栈操作min值已被更新
{
min = min - stack.back();//更新回原来的min值
}
stack.pop_back();
}
}
int top() {
if (stack.empty()) {
return NULL;
}
if (stack.back() > 0) //如果大于0,直接加上min值
{
return stack.back() + min;
}
else{
return min;//小于0,说明当前得x比min小,更新min,也可以同上
}
}
int getMin()
{
if (stack.empty()) {
return NULL;
}
return min;
}
};
int main() {
MinStack s1;
s1.push(1);
s1.push(3);
s1.push(-2);
s1.push(4);
s1.pop();
s1.top();
return 0;
}