前后缀表达式求值顺序栈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;
}
相关推荐
Spiffo_Sir29 分钟前
【Spiffo】光速项目:LVGL v9框架下的MIPI简易相机_Part2
linux·c语言·数码相机
不吃洋葱.1 小时前
力扣448.找到数组中所有消失的元素
数据结构·算法·leetcode
xueyinan1 小时前
小刚说C语言刷题——第21讲 一维数组
c语言
昂子的博客2 小时前
热门面试题第15天|最大二叉树 合并二叉树 验证二叉搜索树 二叉搜索树中的搜索
java·数据结构·算法
ん贤2 小时前
蓝桥杯考前复盘
c语言·c++·算法·职场和发展·蓝桥杯
想成为配环境大佬2 小时前
P8697 [蓝桥杯 2019 国 C] 最长子序列
算法·蓝桥杯·双指针
khazix1012 小时前
【C语言】--- 文件操作
c语言·开发语言
理智的灰太狼3 小时前
题目 2701: 蓝桥杯2022年第十三届决赛真题-取模(C/C++/Java组)
c语言·c++·蓝桥杯
麦麦Max3 小时前
STL-函数对象
开发语言·c++·算法
DeepLink3 小时前
🧠 AI论文精读 :《Attention is All You Need》
人工智能·算法