传说中的数据结构

xiaoxiao2021-02-28  31

 

传说中的数据结构

Time Limit: 1000MS Memory Limit: 65536KB

 

Problem Description

      在大学里学习了一个学期了,大家大都对所学的专业有了基本的了解。许多同学也已经知道了到大二要开一门课叫做《数据结构》,那么今天给你们提前讲一下一个最简单的数据结构:栈。 栈的基本操作有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)。       然后,你们可以看出来了吧,其实栈就是一个先进后出(越先进去的元素越后面出来)的数据结构,很简单吧,下面要检验下你们的学习效果了。

Input

输入包含多组测试数据. 每组数据的第一行为一个整数 T(1 <= T <= 1000 ),接下来 T 行为对栈的操作。

Output

如果操作是top,那么输出最后面的数,如果栈中没有数的话,那就输出“empty”(不含引号)。 如果操作是pop且栈是空的,那么输出 “error”(不含引号)。在每组测试数据的最后多加一次换行。

Example Input

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

Example Output

4 3 empty

 

 

 

 

#include<stdio.h>

#include<string.h> int main(void) {     char str1[5] = "push", str2[4] = "top", str3[4] = "pop", str[8];     int i, n, k, m, a[1000];     while(~scanf("%d", &n))     {          k = -1;          memset(a, 0, sizeof(a));          for(i = 0; i < n; i++)        {          scanf("%s", str);                 //这里不可以使用 gets(), 因为gets()遇到 空格后不会停止, 所以只能使用 scanf()来读入 字符, 因为她遇到空格后就会停止读入。         if(strcmp(str, str1) == 0)         {             scanf("%d", &m);             a[++k] = m;         }         if(strcmp(str, str2) == 0)         {             if(k >= 0)             {                 printf("%d\n", a[k]);             }             else             {                 printf("empty\n");             }         }         if(strcmp(str, str3) == 0)         {             if(k < 0)             {                 printf("error\n");             }             else             {                 k--;             }         }       }       printf("\n");     }    return 0; }

转载请注明原文地址: https://www.6miu.com/read-2400166.html

最新回复(0)