其他分享
首页 > 其他分享> > 栈的应用:中缀表达式转后缀表达式、后缀表达式求值

栈的应用:中缀表达式转后缀表达式、后缀表达式求值

作者:互联网

#pragma once
#include"LinkStack.h"
#include <string>
#include"SqStack.h"
using namespace std;
int getPriority(char a) {
	if (a == '*' || a == '/') {
		return 2;
	}
	else if (a == '-' || a == '+') {
		return 1;
	}
}
bool isOp(char a) {
	if (a == '+' || a == '-' || a == '*' || a == '/') {
		return true;
	}
	else {
		return false;
	}
}
//中缀表达式转后缀
string houzhui(const char* s1) {
	LinkStack opStack;
	InitStack(opStack);
	char a;
	string result = "";
	for (int i = 0; i < strlen(s1); i++) {
		a = s1[i];
		if (isdigit(a)) {
			result += a;
		}
		else if (a == '(') {
			Push(opStack, a);
		}
		else if (isOp(a)) {
			char top;
			while (GetTop(opStack, top) && top != '(' && getPriority(top) >= getPriority(a)) {
				result += top;
				Pop(opStack, top);
			}
			Push(opStack, a);
		}
		else if (a == ')') {
			char top;
			GetTop(opStack, top);
			while (top != '(') {
				result += top;
				Pop(opStack, top);
				GetTop(opStack, top);
			}
			Pop(opStack, top);
		}
	}
	char top;
	while (Pop(opStack, top)) {
		result += top;
	}
	return result;
}
//根据后缀表达式求值
void qiuzhi(const char* s,int &result) {
	SqStack diStack;
	InitStack(diStack);
	int n1, n2;
	for (int i = 0; i < strlen(s); i++) {
		if (isdigit(s[i])) {
			Push(diStack, s[i] - '0');
		}
		else {
			Pop(diStack,n1);
			Pop(diStack, n2);
			switch (s[i])
			{
			case '+':
				Push(diStack, n1 + n2);
				break;
			case '-':
				Push(diStack, n1 - n2);
				break;
			case '*':
				Push(diStack, n1 * n2);
				break;
			case '/':
				Push(diStack, n1 / n2);
				break;
			}
		}
	}
	Pop(diStack, result);
}
#include"qiuzhi.h"
#include <iostream>
int main() {
	string s = "";
	while (cin >> s) {
		int result;
		qiuzhi(houzhui(s.c_str()).c_str(), result);
		cout << result << endl;
	}
	return 0;
}

标签:opStack,中缀,后缀,top,diStack,char,int,result,表达式
来源: https://blog.csdn.net/Warmmm/article/details/113511311