解题思路:解题的关键是用一个链表结构来存储当前栈
中元素最小值的索引,每压入一个元素,该元素与链表
中记录的当前最小元素索引指向的元素比较,如果小于
最小值,将压入元素的索引存入链表中,否则,将原先
最小值的索引继续存储在链表中。举个例子:
栈: 8, 3 , 5, 10, 1
最小元素索引:
0 1 1 1 5
弹出一个元素后:
栈: 8, 3 , 5, 10
最小元素索引:
0, 1 , 1 1
所以,无论是压入或弹出一个元素,栈都可以准确的获取
到当前栈中的最小值。
声明:此题解法非原创,是从一篇博客上看来的,博客地址
已经记不清了,故不在此列出。
源代码:(在VC6下通过编译,正确执行)
#include <stdio.h>
#include <deque>
#include <limits.h>
class StackWithMin
{
public:
bool Empty() const;
int Size() const;
int Top();
void Push(int value);
void Pop();
int Min();
std::deque<int>& getIndexDeq(); //for test;
private:
std::deque<int> m_deq;
std::deque<int> m_minIndexDeq;
};
bool StackWithMin::Empty() const
{
bool b1 = m_deq.empty();
bool b2 = m_minIndexDeq.empty();
return b1&&b2;
}
int StackWithMin::Size() const
{
return m_deq.size();
}
int StackWithMin::Top()
{
return m_deq.back();
}
void StackWithMin::Push(int value)
{
m_deq.push_back(value);
if(m_minIndexDeq.size() <= 0)
m_minIndexDeq.push_back(0);
else
{
int min = m_deq.at(m_minIndexDeq.back());
if(value < min)
m_minIndexDeq.push_back(m_deq.size()-1);
else
m_minIndexDeq.push_back(m_minIndexDeq.back());
}
}
void StackWithMin::Pop()
{
m_deq.pop_back();
m_minIndexDeq.pop_back();
}
int StackWithMin::Min()
{
if(m_deq.size() > 0 && m_minIndexDeq.size() > 0)
return m_deq.at(m_minIndexDeq.back());
else
return INT_MAX;
}
std::deque<int>& StackWithMin::getIndexDeq()
{
return this->m_minIndexDeq;
}
void PrintStack(StackWithMin stack) // for test
{
int sizeDeq = stack.Size();
for(int i = 0; i < sizeDeq; i++)
{
printf("%d--%d ", stack.Top(),stack.getIndexDeq().back());
stack.Pop();
}
printf("/n");
}
int main()
{
StackWithMin stack;
stack.Push(8);
stack.Push(3);
stack.Push(20);
stack.Push(10);
PrintStack(stack);
printf("The min of the stack is: %d/n",stack.Min());
stack.Pop();
stack.Pop();
stack.Push(1);
PrintStack(stack);
printf("The min of the stack is: %d/n",stack.Min());
printf("The top of the stack is: %d/n",stack.Top());
stack.Empty();
return 0;
}