前后缀表达式求值顺序栈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;
}
相关推荐
未来之窗软件服务4 小时前
自己写算法(九)网页数字动画函数——东方仙盟化神期
前端·javascript·算法·仙盟创梦ide·东方仙盟·东方仙盟算法
豐儀麟阁贵4 小时前
基本数据类型
java·算法
程序员老舅6 小时前
干货|腾讯 Linux C/C++ 后端开发岗面试
linux·c语言·c++·编程·大厂面试题
乐迪信息6 小时前
乐迪信息:基于AI算法的煤矿作业人员安全规范智能监测与预警系统
大数据·人工智能·算法·安全·视觉检测·推荐算法
hsjkdhs7 小时前
C++之多层继承、多源继承、菱形继承
开发语言·c++·算法
立志成为大牛的小牛7 小时前
数据结构——十七、线索二叉树找前驱与后继(王道408)
数据结构·笔记·学习·程序人生·考研·算法
星空下的曙光7 小时前
Node.js crypto模块所有 API 详解 + 常用 API + 使用场景
算法·node.js·哈希算法
Algo-hx7 小时前
数据结构入门 (七):从“链接”到“分支” —— 初探树与二叉树
数据结构
小贾要学习8 小时前
【数据结构】C++实现红黑树
数据结构·c++
StarPrayers.9 小时前
旅行商问题(TSP)(2)(heuristics.py)(TSP 的两种贪心启发式算法实现)
前端·人工智能·python·算法·pycharm·启发式算法