【发布时间】:2015-05-11 00:10:38
【问题描述】:
我有一个程序有三个函数,一个是压栈,第二个是从栈中弹出,第三个是检查栈中的最小值。
在推送时检查最小值很容易,因为我们可以在每次新推送时检查最小值是否发生变化。但是,如果用户弹出最小值怎么办,我怎样才能回到之前的最小值呢?我想到了使用节点。我知道我可以使用向量而不是堆栈,但是我想使用堆栈函数并且即使用户弹出最后一个最小值,仍然能够找到最小值。
我们可以用一个节点来跟踪最小数量还是唯一的方法是一个向量?
这是我的代码:
#include <iostream>
#include <stack>
using namespace std;
void myPush(int num, stack<int>& myStack, int &min);
void myPop(stack<int>& myStack, int &min);
int main()
{
int x=0;
int choice;
int n;
int dmin= 2147483646;
stack<int> myStack;
while( x==0) {
cout << "stack menu: " << endl; //this is just a menu
cout << "1- for push " << endl;
cout << "2- for pop " << endl;
cout << "3- for min " << endl;
cout << "4-exit " << endl;
cin >> choice;
if(choice == 1)
{
cout << " I want to push: " << endl;
cin >> n;
myPush(n, myStack, dmin);
}
else if(choice == 2)
{
cout << "popped: " << endl;
myPop(myStack, dmin);
}
else if(choice == 3)
{
cout << "minimum is: " << endl;
cout << dmin;
}
else
x=1; //this will exit the menu
}
}
void myPush(int num, stack<int>& myStack, int &min)
{
if(num <= min) //check if it's the new minimum
min = num;
myStack.push(num); //pushes new num
}
void myPop(stack<int>& myStack, int &min)
{
cout << "popping: " << myStack.top() << endl; //tells the user what we are popping
if( min == myStack.top()) //let the user know that minimum changed(DISASTER!!!)
cout<< "min changed " << endl;
myStack.pop(); //pop that value(Hopefully not the min !)
}
【问题讨论】:
-
放弃被削弱的
std::stack数据结构并使用旧的std::vector。然后您可以使用std::min_element找到最小值。 -
@1nflktd 这根本不是一个好的解决方案。如果他一个接一个地弹出两个最小值怎么办...
-
@Mozein 使用 array-vector- 或任何东西,你会照顾好它
-
只在堆栈上存储对,包含到目前为止的值和最小值。这样,您可以通过从顶部堆栈值中读取最小值来轻松确定最小值,并且弹出顶部对将自动再次为您提供正确的最小值。只有当推送一个新值时,你才需要计算新的最小值以配合它,这很容易。
-
你也可以参考这个。 stackoverflow.com/questions/685060/…
标签: c++