栈 ALDS1_3_A:Stack




这是某本书上的题,书上给的代码有bug

代码:

//草,树上给的代码有bug 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int top,S[1000];
void push(int x)
{
	S[++top]=x;
}
int pop()
{
	top--; 
	return S[top+1];
}
int main()
{
	int a,b;
	top=0;
	char s[100];
	while(scanf("%s",s)!=EOF)  {   // 这不能用EOF,因为他会一直输入下去 
		if( s[0]=='+')  {
			a=pop();
			b=pop();
			push(a+b);
		}  else if(s[0]=='-')  {
			b=pop();
			a=pop();
			push(a-b);
		} else if(s[0]=='*')  {
			a=pop();
			b=pop();
			push(a*b);
		} else {
			push(atoi(s));
		}
	}
	printf("%d\n",pop());
	return 0;
}


改过的代码:

//草,这题有bug 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int top,S[1000];
void push(int x)
{
	S[++top] = x;
}
int pop()
{
	top--; 
	return S[top+1];
}
int main()
{
	int a,b;
	top=0;
	char s[100];
	while(scanf("%s", s),s[0]!='m')  {  //s[0]!='m',m是输入的结束标志防止上述股情况发生 
		if( s[0] == '+')  {
			a=pop();
			b=pop();
			push(a + b);
		}  else if(s[0] == '-')  {
			b=pop();
			a=pop();
			push(a - b);
		} else if(s[0] == '*')  {
			a=pop();
			b=pop();
			push(a * b);
		} else {
			push(atoi(s));
		}
	}
	printf("%d\n", pop());
	return 0;
}
//  输入:
// 1 2 + 3 4 - *



自己写的代码:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <stack>
using namespace std;
int main()
{
	int a,b;
	stack<int > sta;
	char s[100];
	while(scanf("%s", s)!=EOF)  {
		if( s[0] == '+')  {
			a=sta.top();
			sta.pop();
			b=sta.top();
			sta.pop();
			sta.push(a + b);
		}  else if(s[0] == '-')  {
			b=sta.top();
			sta.pop();
			a=sta.top();
			sta.pop();
			sta.push(a - b);
		} else if(s[0] == '*')  {
			a=sta.top();
			sta.pop();
			b=sta.top();
			sta.pop();
			sta.push(a * b);
		} else {
			sta.push(atoi(s));
		}
		printf("%d\n", sta.top());
	}
	printf("%d\n", sta.top());
	return 0;
}
//   1 2 + 3 4 - *












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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值