棧 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 - *












發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章