数据结构实验之栈三:后缀式求值
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
输入
输出
示例输入
59*684/-3*+#
示例输出
57
提示
后缀表达式求值:当输入的字符是数字时直接入栈,当输入的字符在是运算符时,每一个操作符用于运算它前面的两个数字,得出的结果也作为一个数字入栈。遍历字符串数组结束后弹出栈顶元素,即为结果。
#include <stdio.h>
#include <stdlib.h>#include <string.h>
typedef struct {
int *base;
int *top;
int Lsize;
}Sqstack;
Sqstack Create(Sqstack &s)
{
s.base=(int *)malloc(1010*sizeof(int ));
s.top=s.base;
return s;
}
Sqstack push(Sqstack &s,int e){
*s.top++=e;
}
int gettop(Sqstack &s)
{
int e;
e=*(s.top-1);
return e;
}
int pop(Sqstack &s){
int a;
if(s.top==s.base)return -1;
s.top--;
a=*s.top;
return a ;
}
int Empty(Sqstack &s){
if(s.top==s.base) return 1;
else return 0;
}
int clearstack(Sqstack &s){
s.top=s.base;
}
int main()
{
int i,len,j,x,y;
char a[1001];
int b[1001];
Sqstack S;
S=Create(S);
scanf("%s",a);
len=strlen(a);
for(i=0;i<len-1;i++){
if(a[i]<='9'&&a[i]>='0'){
push(S,a[i]-48);
}
else if(a[i]=='+'){
y=gettop(S);
pop(S);
x=gettop(S);
pop(S);
push(S,x+y);
}
else if(a[i]=='-'){
y=gettop(S);
pop(S);
x=gettop(S);
pop(S);
push(S,x-y);
}
else if(a[i]=='*'){
y=gettop(S);
pop(S);
x=gettop(S);
pop(S);
push(S,x*y);
}
else if(a[i]=='/'){
y=gettop(S);
pop(S);
x=gettop(S);
pop(S);
push(S,x/y);
}
}
j=gettop(S);
printf("%d",j);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int *base;
int *top;
int Lsize;
}Sqstack;
Sqstack Create(Sqstack &s)
{
s.base=(int *)malloc(1010*sizeof(int));
s.top=s.base;
return s;
}
Sqstack push(Sqstack &s,int e){
*s.top++=e;
}
int gettop(Sqstack &s)
{
int e;
e=*(s.top-1);
return e;
}
int pop(Sqstack &s){
int a;
if(s.top==s.base)return -1;
s.top--;
a=*s.top;
return a ;
}
int Empty(Sqstack &s){
if(s.top==s.base) return 1;
else return 0;
}
int clearstack(Sqstack &s){
s.top=s.base;
}
int main()
{
int i,j,len,x,y;
char a[1001];
int b[1001];
Sqstack S;
S=Create(S);
scanf("%s",&a);
len=strlen(a);
for(i=0;i<len-1;i++){
if(a[i]=='1'){
b[i]=1;
push(S,b[i]);
}else if(a[i]=='2'){
b[i]=2;
push(S,b[i]);
}
else if(a[i]=='3'){
b[i]=3;
push(S,b[i]);
}
else if(a[i]=='4'){
b[i]=4;
push(S,b[i]);
}
else if(a[i]=='5'){
b[i]=5;
push(S,b[i]);
}
else if(a[i]=='6'){
b[i]=6;
push(S,b[i]);
}
else if(a[i]=='7'){
b[i]=7;
push(S,b[i]);
}
else if(a[i]=='8'){
b[i]=8;
push(S,b[i]);
}
else if(a[i]=='9'){
b[i]=9;
push(S,b[i]);
}
else if(a[i]=='+'){
y=gettop(S);
pop(S);
x=gettop(S);
pop(S);
push(S,x+y);
}
else if(a[i]=='-'){
y=gettop(S);
pop(S);
x=gettop(S);
pop(S);
push(S,x-y);
}
else if(a[i]=='*'){
y=gettop(S);
pop(S);
x=gettop(S);
pop(S);
push(S,x*y);
}
else if(a[i]=='/'){
y=gettop(S);
pop(S);
x=gettop(S);
pop(S);
push(S,x/y);
}
}
j=gettop(S);
printf("%d",j);
}