前后缀表达式求值顺序栈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;
}
相关推荐
大数据张老师5 分钟前
数据结构——邻接矩阵
数据结构·算法
低音钢琴40 分钟前
【人工智能系列:机器学习学习和进阶01】机器学习初学者指南:理解核心算法与应用
人工智能·算法·机器学习
傻童:CPU3 小时前
C语言需要掌握的基础知识点之前缀和
java·c语言·算法
degen_3 小时前
第一次进入 PEICORE 流程
c语言·笔记
深思慎考3 小时前
从合并两个链表到 K 个链表:分治思想的递进与堆优化
数据结构·链表·递归··队列·合并链表
又见野草3 小时前
软件设计师知识点总结:数据结构与算法(超级详细)
数据结构·算法·排序算法
我是大咖3 小时前
C语言-贪吃蛇项目开发工具篇---ncursee库安装
c语言·开发语言
GalaxyPokemon3 小时前
有一个服务器,用于提供HTTP服务,但是需要限制每个用户在任意的100秒内只能请求60次,怎么实现这个功能
算法
czy87874753 小时前
用C语言实现单例模式
c语言·单例模式
fl1768314 小时前
基于opencv+Mediapipe+CNN实现用手势识别控制对鼠标操控python源码+项目说明+设计文档
算法