您的位置:首页 > 理论基础 > 数据结构算法

传说中的数据结构

2014-08-12 09:31 197 查看

传说中的数据结构


Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^

题目描述

在大学里学习了一个学期了,大家大都对所学的专业有了基本的了解。许多同学也已经知道了到大二要开一门课叫做《数据结构》,那么今天给你们提前讲一下一个最简单的数据结构:栈。 栈的基本操作有3种:push,pop,top。

例如,给你一个数列:1 2 3 4

push:向栈中加入一个数,比如push 5,数列就变成1 2 3 4 5。

pop:从栈中删除最后面的数,比如 pop,数列就变成1 2 3。(数列变化,但是不输出。如果栈是空的,即不能 pop 操作,那就输出 error ,但是接下来的操作还是要继续的)。

top:找出栈最后面的数,比如 top ,你就要输出4。(如果栈中没有数的话,即不能 top 操作,那就输出 empty)。

然后,你们可以看出来了吧,其实栈就是一个先进后出(越先进去的元素越后面出来)的数据结构,很简单吧,下面要检验下你们的学习效果了。

输入

输入包含多组测试数据.

每组数据的第一行为一个整数 T(1 <= T <= 1000 ),接下来 T 行为对栈的操作。

输出

如果操作是top,那么输出最后面的数,如果栈中没有数的话,那就输出“empty”(不含引号)。

如果操作是pop且栈是空的,那么输出 “error”(不含引号)。

在每组测试数据的最后多加一次换行。

示例输入

8
push 1
push 2
push 3
push 4
top
pop
top
pop
3
push 1
pop
top


示例输出

4
3

empty


提示

来源

qinchuan
方法一:数组模拟栈的过程
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;
int main()
{
int T, i, n ;
int stack[1000] ;
char str[1000] ;
while(scanf("%d",&T)!=EOF)
{
int top = 0;
for(i=0; i<T; i++)
{
scanf("%s",str) ;
if(strcmp(str, "push")==0)
{
scanf("%d", &n) ;
stack[top++] = n ;
}
if(strcmp(str, "pop")==0)
{

if(top==0)
{
printf("error\n") ;
continue ;
}
else
stack[top--] ;
}
if(strcmp(str, "top")==0)
{
if(top==0)
{
printf("empty\n") ;
continue ;
}
else
printf("%d\n", stack[top-1]) ;
}
}
printf("\n") ;
}
return 0 ;
}
<strong><span style="font-size:18px;">方法二:用STL栈的思想</span></strong>
<strong><span style="font-size:18px;">代码如下:</span></strong>
<pre class="html" name="code">#include <stack>
#include <string>
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
int T;
char s[100];
while(cin>>T)
{
stack<int> q;
for(int i=0;i<T;i++)
{

cin>>s;          //操作判断
if(strcmp(s,"push")==0)
{
int n;
cin>>n;
q.push(n);//进栈
continue;
}
else if(strcmp(s,"top")==0)
{
if(q.empty())
{
cout<<"empty"<<endl;   //清空判断
}
else
{
cout<<q.top()<<endl;
}
continue;
}
else if(strcmp(s,"pop")==0)
{
if(q.empty())
{
cout<<"error"<<endl;
}
else
{
q.pop();      //删除第一个元素
}
continue;
}

}
cout<<endl;//注意要求,多空一行
}
return 0;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: