您的位置:首页 > 其它

题目1512:用两个栈实现队列 && 包含min函数的栈

2013-06-28 00:30 399 查看
题目描述:

用两个栈来实现一个队列,完成队列的Push和Pop操作。

队列中的元素为int类型。

输入:

每个输入文件包含一个测试样例。

对于每个测试样例,第一行输入一个n(1<=n<=100000),代表队列操作的个数。

接下来的n行,每行输入一个队列操作:

1. PUSH X 向队列中push一个整数x(x>=0)

2. POP 从队列中pop一个数。

输出:

对应每个测试案例,打印所有pop操作中从队列pop中的数字。如果执行pop操作时,队列为空,则打印-1。

样例输入:
3
PUSH 10
POP
POP

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;

int s1[100001],s2[100001];
int top1,top2;

int pop(){
if(top2 < 0){
while(top1 >= 0)
s2[++top2] = s1[top1--];
}
if(top2 < 0)
return -1;
else
return s2[top2--];
}

int main(int argc, char const *argv[])
{
int n,x;
char op[4];
while(scanf("%d",&n) != EOF){
top1 = top2 = -1;
for(int i = 0;i < n;i++){
scanf("%s",op);
if(!strcmp(op,"PUSH")){
scanf("%d",&x);
s1[++top1] = x;
}
if(!strcmp(op,"POP"))
printf("%d\n",pop());
}
}
return 0;
}


[/code]

样例输出:
10
-1


题目描述:
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的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 <cstdio>
#include <iostream>
#include <list>
#include <stack>
#include <algorithm>
using namespace std;

stack<int> s1,s2;

int main(int argc, char const *argv[])
{
int n,x;
char s[3];
while(scanf("%d",&n) != EOF){
while(n--){
scanf("%s",s);
if(s[0] == 's'){
scanf("%d",&x);
if(s2.empty() || (s2.top() > x)){
s2.push(x);
}else
s2.push(s2.top());
s1.push(x);
}
else{
if(!s1.empty()){
s1.pop();
s2.pop();
}else{
printf("NULL\n");
continue;
}
}
if(!s1.empty())
printf("%d\n",s2.top());
else
printf("NULL\n");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: