思路: 根据输入的字符串 遇到数字 入栈 ,遇到运算符弹出两个数字计算,计算结果入栈,最后栈中剩余的数字就是最终结果。
代码示例:
//后缀表达式求解
void Postfix(char str[], Stack S)
{
int i = 0, t1, t2;
while (str[i] != '\0')
{
//数字入栈
while (isdigit(str[i]))
Push((str[i++]-48), S);
//操作符出栈2个数,结果入栈
t1 = Top(S);
Pop(S);
t2 = Top(S);
Pop(S);
switch (str[i])
{
case '+':
Push(t1 + t2, S);
break;
case '-':
Push(t1 - t2, S);
break;
case '*':
Push(t1 * t2, S);
break;
case '/':
Push(t1 / t2, S);
break;
default:
printf("error");
break;
}
i++;
}
printf("%d",Top(S));
}
完整程序:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
//栈的定义
struct Node
{
int Capacity; //容量
int TopOfStack; //栈顶
int *Array;
} Node;
typedef struct Node *Stack, *PtrNode;
//创建栈
Stack CreatStack(int Max)
{
Stack S;
S = (PtrNode)malloc(sizeof(struct Node));
if (S == NULL)
printf("create stack error");
S->Array = (int *)malloc(Max * sizeof(int));
if (S->Array == NULL)
printf("create stack error");
S->Capacity = Max;
S->TopOfStack = -1;
return S;
}
int IsFull(Stack S)
{
return S->TopOfStack == S->Capacity - 1;
}
int IsEmpty(Stack S)
{
return S->TopOfStack == -1;
}
void Push(char x, Stack S)
{
if (IsFull(S))
printf("stack is full");
else
{
S->TopOfStack = S->TopOfStack + 1;
S->Array[S->TopOfStack] = x;
}
// S->Array[++S->TopOfStack] = x;
}
void Pop(Stack S)
{
if (IsEmpty(S))
printf("stack is empty");
else
S->TopOfStack--;
}
char Top(Stack S)
{
if (IsEmpty(S))
printf("stack is empty");
else
return S->Array[S->TopOfStack];
}
//后缀表达式求解
void Postfix(char str[], Stack S)
{
int i = 0, t1, t2;
while (str[i] != '\0')
{
//数字入栈
while (isdigit(str[i]))
Push((str[i++]-48), S);
//操作符出栈2个数,结果入栈
t1 = Top(S);
Pop(S);
t2 = Top(S);
Pop(S);
switch (str[i])
{
case '+':
Push(t1 + t2, S);
break;
case '-':
Push(t1 - t2, S);
break;
case '*':
Push(t1 * t2, S);
break;
case '/':
Push(t1 / t2, S);
break;
default:
printf("error");
break;
}
i++;
}
printf("%d",Top(S));
}
int main()
{
char str[100];
printf("please input postfix expression\n");
scanf("%s", str);
int len = strlen(str);
Stack S;
S = CreatStack(len+1);
Postfix(str, S);
}