数据结构——栈的使用

TOJ 1218

描述

请你定义一个栈,可以对栈进行“压入堆栈”、“弹出栈顶元素”、“清空堆栈”、“获取栈顶元素”等操作。键盘输入一些命令,可以执行上述操作。本题中,栈元素均为整数。栈的最大元素个数为1000。

输入

输入各个命令它们对应的格式如下:

压入堆栈:push a,a代表压入堆栈的元素,这里push和元素之间用空格分隔。

清空堆栈:clear

获取栈顶元素:top

弹出栈顶元素:pop

当输入的命令为exit时,程序结束。

输出

当输入的命令为pop时,请输出弹出的元素值。

当输入的命令是top时,请输出当前栈顶元素值。

注意,如果没有满足的元素,请输出None。

样例输入

样例输出


其实这个不用堆栈,直接用数组也能做....

#include<stdio.h>
#include<string.h>
int main()
{
	char a[10],ch,c[10];int b[1000],i=0,s=0,j;
	while(1)
	{
		scanf("%s",a);
		if(a[0]=='e')break;
		else if(a[0]=='p'&&a[1]=='u')
		{
			while((ch=getchar())!=EOF)
			{
				if(ch=='\n')
				break;
				else
				{
					s=0;
					scanf("%s",c);
					j=0;
					while(j!=strlen(c))
					{
						s=s*10+c[j]-'0';
						j++;
					}
					b[i++]=s;
				}
			}
		}
		else if(a[0]=='t')
		{
			if(i-1<0)printf("None\n");
			else printf("%d\n",b[i-1]);
		}
		else if(a[0]=='p')
		{
			if(i-1<0)printf("None\n");
			else printf("%d\n",b[i-1]),i--;
		}
		else if(a[0]=='c')i=0;
	}
}

但是题目都写了用栈了..我还是乖乖用栈吧..

注意点1:下标从0开始,但是存数字是从1开始的。

2.最后存进去的是栈顶,最早的是底。所以栈顶元素值top是最后输入的值。

#include <stdio.h>
#include <string.h>
int top,s[1001];
void push(int x)
{
	s[++top]=x;
}
int pop()
{
	top--;
	return s[top+1];
}
void clear()
{
	int i;
	for(i=0;i<top;i++)
	{	
		s[i]=0;
	}
	top=0;
} 
int main()//1218
{
	char a[10];
	int n;
	top=0;
	while(scanf("%s",a))
	{
		if(strcmp(a,"exit")==0)break;
		
		if(strcmp(a,"push")==0)
		{
			scanf("%d",&n);
			push(n);
		}
		else if(strcmp(a,"pop")==0)
		{
			if(top==0)
			printf("None\n");
			else
			printf("%d\n",pop());
		}
		else if(strcmp(a,"top")==0)
		{
			if(top==0)
			printf("None\n");
			else
			printf("%d\n",s[top]);
		}
		else if(strcmp(a,"clear")==0)
		clear();
	}
} 


这道题真是历尽坎坷啊..最后还是抱着视死如归的心态去问的crq老师..

阿西吧...

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值