Say a few days ago little Q go to company interview ...
Interviewer: Do you know the stack of this data structure.
Little Q: You know, Balabala ...
Interviewer: Well, now, please implement such a stack, in addition to pop,top,push three operations, but also need to include the minimum value of the query stack min operation.
Small Q: That simple Ah, query the minimum value of the time to traverse the stack can be.
Interviewer: ...
Interviewer: Today's interview is here, you go home and wait for the notice to go.
.....................
No doubt, Little Q this interview is dead and can not die. In order to avoid the same mistake, small q to as Acmer Zeratul for help. But Zeratul just in Qingdao dozen iron, is crying unintentionally answer questions, so little Q found the same as Acmer you. Can you help him solve the problem?
Prepare two stacks, one is normal to save the number, and the other is the minimum worth of the record stack.
Stack-stack condition for minimum values: The new number is less than the element equal to the top of the current stack.
The minimum stack condition: The number of stacks equals the element value at the top of the current stack.
Note: The initial value of the minimum stack is initialized to 0x3f3f3f3f
Code:
#include <iostream> #include <stdio.h> #include <stack> using namespace std;
int main () {stack<int> stack1;
Stack<int> stackmin;
int stack1num = 0;
int stackminnum = 0;
int T;
int oper;
int opernum;
Stackmin.push (0x3f3f3f3f);
scanf ("%d", &t);
for (int i = 0;i < T;i + +) {scanf ("%d", &oper);
if (oper = = 0) {scanf ("%d", &opernum);
Stack1.push (Opernum);
Stack1num + +;
if (Opernum <= stackmin.top ()) {Stackmin.push (opernum);
Stackminnum + +;
}}else if (oper = = 1) {if (stack1num>0) {printf ("%d\n", Stack1.top ());
}else{printf ("error!\n");
}}else if (oper = = 2) {if (stackminnum>0) {printf ("%d\n", Stackmin.top ());
}else{printf ("error!\n"); }}else if (oper = = 3) {if (stack1num>0) {int top = Stack1.top ();
Stack1.pop ();
Stack1num--;
if (top = = Stackmin.top ()) {Stackmin.pop ();
Stackminnum--;
}}else{printf ("error!\n");
}} return 0;
}