SDUT-2556 传说中的数据结构


Code
#include <stdio.h>
#include <string.h>

int main()
{
    int t,stack[1000];
    char act[10];
    while(~scanf("%d",&t))
    {
        int k = 0;
        while(t--)
        {
            scanf("%s",act);
            if(strcmp(act,"push") == 0)
            {
                scanf("%d",&stack[k++]);
            }
            if(strcmp(act,"pop") == 0)
            {
                if(k < 1)
                {
                    printf("error\n");
                }
                else
                {
                    k--;
                }
            }
            if(strcmp(act,"top") == 0)
            {
                if(k == 0)
                    printf("empty\n");
                else
                    printf("%d\n",stack[k-1]);
            }
        }
        printf("\n");
    }
    return 0;
}
反思:字符串练习,用一个stack数组模拟栈结构,用strcmp()函数判断操作,用k模拟栈的top指针。

更新:大二学习了数据结构,试着用了C++STL的stack实现。注意每次读入n后要清空栈。

Code - C++
#include <iostream>
#include <string>
#include <stack>

using namespace std;


int main()
{
    int n, num;
    string op;
    stack <int> S;
    while(cin >> n)
    {
        while(!S.empty())
            S.pop();
        while(n--)
        {

            cin >> op;
            if(op == "push")
            {
                cin >> num;
                S.push(num);
            }
            else if(op == "top")
            {
                if(S.empty())
                    cout << "empty" << endl;
                else
                    cout << S.top() << endl;
            }
            else if(op == "pop")
            {
                if(S.empty())
                    cout << "error" << endl;
                else
                    S.pop();
            }
        }
        cout << endl;
    }
    return 0;
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值