代码
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#include <ctype.h>
struct StackRecord
{
int Capacity;
int TopOfStack;
int *Array;
};
typedef struct StackRecord *Stack;
Stack CreateStack(int MaxElem)
{
Stack S;
S=(StackRecord *)malloc(sizeof(struct StackRecord));
if(S==NULL)
printf("Out of space!1");
S->Array=(int *)malloc(sizeof(int)*MaxElem);
if(S->Array==NULL)
printf("Out of space!2");
S->Capacity=MaxElem;
S->TopOfStack=-1;
return S;
}
void DisposeStack(Stack S)
{
if(S!=NULL)
{
free(S->Array);
free(S);
}
}
int IsEmpty(Stack S)
{
return S->TopOfStack==-1;
}
int IsFull(Stack S)
{
return S->TopOfStack==S->Capacity-1;
}
void Push(Stack S,int x)
{
if(IsFull(S))
printf("Out of space!3");
else
S->Array[++S->TopOfStack]=x;
}
int Top(Stack S)
{
if(IsEmpty(S))
{
printf("Empty Stack!");return 0;
}
else
return S->Array[S->TopOfStack];
}
void Pop(Stack S)
{
if(IsEmpty(S))
printf("Empty Stack!");
else
S->TopOfStack--;
}
int main(void) {
char str[100];
int num1,num2,sum;
scanf("%s",str);
int length=strlen(str);
Stack S=CreateStack(length+1);
for (int i=0;i<length;i++)
{
if(isdigit(str[i]))
{
int d=str[i]- '0';
Push(S,d);
}
else if(str[i]=='+')
{
num1=Top(S);
Pop(S);
num2=Top(S);
Pop(S);
sum=(num1+num2);
Push(S,sum);
}
else if(str[i]=='-')
{
num1=Top(S);
Pop(S);
num2=Top(S);
Pop(S);
sum=(num1-num2);
Push(S,sum);
}
else if(str[i]=='*')
{
num1=Top(S);
Pop(S);
num2=Top(S);
Pop(S);
sum=(num1*num2);
Push(S,sum);
}
else if(str[i]=='/')
{
num1=Top(S);
Pop(S);
num2=Top(S);
Pop(S);
sum=(num1/num2);
Push(S,sum);
}
}
printf("%d",Top(S));
}
输入:1234-*+42/-
输出:-3