前后缀表达式求值顺序栈C语言

c 复制代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MaxSize 50
typedef int  ElemType;
typedef struct {
	ElemType data[MaxSize];
	int top;
}SqStack;
void InitStack(SqStack& S) {
	S.top = -1;
}
int StackEmpty(SqStack& S) {
	if (S.top == -1)
		return 1;
	else
		return 0;
}
void Push(SqStack& S, ElemType e) {
	if (S.top == MaxSize - 1)
		return;
	S.data[++S.top] = e;

}
void Pop(SqStack& S, ElemType& e) {
	if (S.top == -1)
		return;
	e = S.data[S.top--];
}
int GetTop(SqStack& S) {
	int e = S.data[S.top];
	return e;
}
int compulate(int x1,char f,int x2) {
	int e1 = x1;
	int e2 = x2;
	int res=0;
	switch (f) {
	case '+':
		res = e1 + e2;
		break;
	case '-':
		res = e1 - e2;
		break;
	case '*':
		res = e1 * e2;
		break;
	case '/':
		res = e1 / e2;
		break;
	}
	return res;
	
}
int zhong(SqStack& S1,SqStack ) {

}
int qian(SqStack& S, char* s) {//前缀表达式求值
	int length = strlen(s);
	for (int i = length-1; i >= 0; i--) {
		if (s[i] >= '0' && s[i] <= '9') {
			Push(S, s[i] - '0');
		}
		else {
			int e1, e2;
			Pop(S, e1);
			Pop(S, e2);
			printf("%d%c%d=%d\n", e1, s[i], e2, compulate(e1, s[i], e2));
			Push(S, compulate(e1, s[i], e2));
		}
	}
	char e;
	e = GetTop(S);
	return e;
}
int hou(SqStack &S,char *s) {//后缀表达式求值
	int length = strlen(s);
	for (int i = 0; i<length; i++) {
		if (s[i] >= '0' && s[i] <= '9') {
			Push(S, s[i]-'0');
		}
		else {
			int e1, e2;
			Pop(S, e1);
			Pop(S, e2);
			printf("%d%c%d=%d\n", e2, s[i], e1, compulate(e2, s[i], e1));
			Push(S, compulate(e2,s[i],e1));
		}
	}
	char e;
	e=GetTop(S);
	return e ;
}

int main() {

	char s[10];//用一个字符数组存储后缀表达式
	gets_s(s);
	SqStack S;
	InitStack(S);
	int x = qian(S,s);
	printf("%d", x);
	return 0;
}
相关推荐
愈谦卑20 分钟前
数据结构:排序
数据结构·算法·排序算法
好记性+烂笔头29 分钟前
hot100_108. 将有序数组转换为二叉搜索树
算法·leetcode·职场和发展
tt55555555555540 分钟前
每日一题——主持人调度(二)
c语言·数据结构·算法·leetcode·八股文
技术蔡蔡1 小时前
Android字节码处理-函数耗时统计揭秘
算法·面试
qing_0406031 小时前
数据结构——二叉搜索树
数据结构·c++·二叉树·二叉搜索树
Felven1 小时前
B. Skibidus and Ohio
算法
yonuyeung1 小时前
代码随想录算法【Day54】
java·数据结构·算法
敲上瘾2 小时前
基础dp——动态规划
java·数据结构·c++·python·算法·线性回归·动态规划
西猫雷婶2 小时前
python学智能算法(三)|模拟退火算法:深层分析
算法·机器学习·模拟退火算法
张有志_2 小时前
STL容器终极解剖:C++ vector源码级实现指南 | 从内存分配到异常安全的全流程避坑
c语言·c++·算法·开源·visual studio