您的位置:首页 > 其它

题目1522:包含min函数的栈

2013-09-16 23:58 316 查看
题目描述:

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

输入:

输入可能包含多个测试样例,输入以EOF结束。

对于每个测试案例,输入的第一行为一个整数n(1<=n<=1000000), n代表将要输入的操作的步骤数。

接下来有n行,每行开始有一个字母Ci。

Ci=’s’时,接下有一个数字k,代表将k压入栈。

Ci=’o’时,弹出栈顶元素。

输出:

对应每个测试案例中的每个操作,

若栈不为空,输出相应的栈中最小元素。否则,输出NULL。

样例输入:
7
s 3
s 4
s 2
s 1
o
o
s 0


样例输出:
3
3
2
1
2
3
0


#include<iostream>
#include<cstdio>
#include<stack>
#define inf 1000000002
using namespace std ;
int main(void)
{
int n , min1;
while(scanf("%d",&n)!=EOF)
{
min1 = inf ;
stack<int>s1 , s2  ;
while(n--){
char ch[6] ;
int cnt ;
scanf("%s",ch);
if(ch[0] == 's')
{
scanf("%d",&cnt);
s1.push(cnt);
if(s2.empty() || s2.top()>cnt)
s2.push(cnt);
else
s2.push(s2.top());
}
else
{
if(!s1.empty())
{
s1.pop();
s2.pop();
}
}
if(!s2.empty())
printf("%d\n",s2.top());
else
printf("NULL\n");
}
}
return 0 ;
}


#include<iostream>
#include<stdio.h>
#include<string.h>
#include<stack>
using namespace std;
int main()
{
int n,i;
stack<int> st;
int min;
scanf("%d",&n);
for(i=0;i<n;i++){
char ch[2];
int tmp;
scanf("%s",ch);
if(ch[0]=='s'){
scanf("%d",&tmp);
if(st.empty()){
st.push(tmp);
min=tmp;
}
else if(tmp<min)
{
st.push(tmp-min);
min=tmp;
}
else{
st.push(tmp);
}
}
else{
if(!st.empty()){
if(st.top()<0)
min=min-st.top();
st.pop();
}
}
if(!st.empty())
printf("%d\n",min);
else
printf("NULL\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: