用数组模拟栈

20 篇文章 0 订阅
17 篇文章 0 订阅
#include <iostream>
#include  <cstring>

using namespace std;

const int N =100010;
int str[N];
int tt=-1;
//向栈顶加上一个元素
void push(int x){
    str[++tt]=x;
}
//弹出栈顶的一个元素
void pop(){
    str[tt]=NULL;
    tt--;
}
//判断是否栈里有值
int empty(){
    if(tt>=0){
        return -1;
    }else{
        return 1;
    }
}
//查询栈的顶头元素
int query(){
    return str[tt];
}
int main(){
	int n;
	char ch[10];
	scanf("%d",&n);
	while(n--){
		int a;
		scanf("%s",&ch);
		if(n==0){
			getchar();
		}
		if(strcmp(ch,"push")==0){
			scanf("%d",&a);
			push(a);
		}
		if(strcmp(ch,"pop")==0){
			pop();
		}
		if(strcmp(ch,"query")==0){
			int a =query();
		    printf("%d\n",a);
		}
		if(strcmp(ch,"empty")==0){
			int a= empty();
			if(a==-1){
				printf("NO\n");
			}
			else{
				printf("YES\n");
			}
		}
	}
	return 0;
}

写了一道用数组模拟栈的题目很简单就不解释啥了

对了,在写这个题目的时候,我发现了一个问题,就是说scanf("%s",&a);并不能把字符串输入进去,只能用于输入字符串数组,但是cin>>就可以

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值