您的位置:首页 > 其它

题目1522:包含min函数的栈

2015-03-10 12:33 169 查看
创建2个栈,一个存放题目数字,另一个把当前最小值压入栈中。

栈顶的就是最小值

#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
stack<int>st1;
stack<int>st2;
int main()
{
	int n;
	while(scanf("%d",&n) != EOF)
	{
		while(!st1.empty())
			st1.pop();
		while(!st2.empty())
			st2.pop();
		char ch[2];
		while(n--)
		{
			scanf("%s",ch);
			if(ch[0] == 's')
			{
				int val;
				scanf("%d",&val);
				if(st2.empty() || st2.top() >= val)
				{
					st2.push(val);
				}
				st1.push(val);
				printf("%d\n",st2.top());
			}
			else
			{
				if(st1.empty())
				{
					printf("NULL\n");
				}
				else
				{
					int val = st1.top();
					st1.pop();
					if(val == st2.top())
					{
						st2.pop();
					}
					if(st2.empty())  //这儿没判定,RE了3次,郁闷 
					{
						printf("NULL\n");
					}
					else
					{
						printf("%d\n",st2.top());
					}
					
				}
			}
		}
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: