前后缀表达式求值顺序栈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;
}
相关推荐
superman超哥4 小时前
仓颉语言中元组的使用:深度剖析与工程实践
c语言·开发语言·c++·python·仓颉
LYFlied5 小时前
【每日算法】LeetCode 153. 寻找旋转排序数组中的最小值
数据结构·算法·leetcode·面试·职场和发展
唐装鼠5 小时前
rust自动调用Deref(deepseek)
开发语言·算法·rust
ytttr8736 小时前
MATLAB基于LDA的人脸识别算法实现(ORL数据库)
数据库·算法·matlab
charlie1145141916 小时前
现代嵌入式C++教程:C++98——从C向C++的演化(2)
c语言·开发语言·c++·学习·嵌入式·教程·现代c++
雨季余静6 小时前
c语言 gb2312转utf-8,带码表,直接使用。
c语言·c语言utf8·c语言gb2312·c语言gbk·c语言gb18030·gb2312转utf8·gbk转utf8
2401_890443026 小时前
Linux 基础IO
linux·c语言
jianfeng_zhu7 小时前
整数数组匹配
数据结构·c++·算法
yueqingll7 小时前
032、数据结构之代码时间复杂度和空间复杂度的判断:从入门到实战
数据结构
smj2302_796826527 小时前
解决leetcode第3782题交替删除操作后最后剩下的整数
python·算法·leetcode