C语言 表达式转换 中缀表达式转后缀表达式

算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。

输入格式:

输入在一行中给出不含空格的中缀表达式,可包含+-*\以及左右括号(),表达式不超过20个字符。

输出格式:

在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。

输入样例:

2+3*(7-4)+8/4

输出样例:

2 3 7 4 - * + 8 4 / +

解题思路:

这道题比较混蛋,很混蛋,他也咩有告诉你到底是什么数字,而且还把“/”给打反了打成了“\”,其次呢,对于数字的输入不只是一位整数,而是:正负都有的多位小数输入 。骗子,曰噢。

我的处理办法是用string::iterator来记录当前扫描到的位置,然后用这个iterator来进行数字的单独识别,其他情况按照逆波兰算法处理就好,其他博主的文章写的已经很多了,原理就不再赘述了,此处留下博主的一种实现方案。

代码:

#include <iostream>
#include <map>
#include <stack>
#include <vector>

using namespace std;

typedef map<char, int> TokenLevel;

vector<string> reversePolishNotation(const string& expression, const TokenLevel& tokenLevel);
string readNumber(string::const_iterator& it, const string& expression);
int main() {
	const TokenLevel tokenLevel{
		{'+', 1},{'-', 1},
		{'*', 2},{'/', 2},
		{'(', 0},{')', 0}
	};

	string inputExpression;
	cin >> inputExpression;

	auto res = reversePolishNotation(inputExpression, tokenLevel);
	cout << res[0];
	for (int i = 1; i < res.size(); i++) {
		cout << " " << res[i];
	}

	return 0;
}

inline bool checkNumber(string::const_iterator& it, const string& expression) {
	return isdigit(*it) ||
		(it == expression.begin() || *(it - 1) == '(') && (*it == '-' || *it == '+') ||
		*it == '.' && isdigit(*(it + 1));
}
string readNumber(string::const_iterator& it, const string& expression) {
	string rtn;
	while (it != expression.end() && checkNumber(it, expression))
		if (*it != '+') rtn += *it++; else ++it;
	return rtn;
}

vector<string> reversePolishNotation(const string& expression, const TokenLevel& tokenLevel) {
	vector<string> result;
	vector<char> buffer;
	for (auto it = expression.begin(); it != expression.end();) {
		auto ch = *it;
		if (!checkNumber(it, expression)) {
			if (ch == '(' || buffer.empty()) {
				buffer.push_back(ch);
			} else if (ch == ')') {
				while (buffer.back() != '(') {
					result.push_back(string{ buffer.back() });
					buffer.pop_back();
				}
				buffer.pop_back();
			} else {
				if (tokenLevel.at(ch) <= tokenLevel.at(buffer.back())) {
					while (!buffer.empty() && tokenLevel.at(ch) <= tokenLevel.at(buffer.back())) {
						result.push_back(string{ buffer.back() });
						buffer.pop_back();
					}
				}
				buffer.push_back(ch);
			}++it;
		} else result.push_back(readNumber(it, expression));
	}

	while (!buffer.empty()) {
		result.push_back(string{ buffer.back() });
		buffer.pop_back();
	}
	return result;
}

当然,博主为什么这么写呢,当然是为了可读性可维护性还有可扩展性啦。

举个🌰

inline bool checkNumber(string::const_iterator& it, const string& expression);

中的isdigit数字判定改为isalnum之后,就可以解析单词啦o(* ̄▽ ̄*)ブ

inline bool checkNumber(string::const_iterator& it, const string& expression) {
	return isalnum(*it) ||
		(it == expression.begin() || *(it - 1) == '(') && (*it == '-' || *it == '+') ||
		*it == '.' && isalnum(*(it + 1));
}

测试

结尾:

(´▽`ʃ♡ƪ) over~

就这。

前缀表达式中缀表达式转换后缀表达式的方法是类似的,都可以利用栈来实现。 对于前缀表达式,我们可以从右往左遍历,遇到操作数直接输出到后缀表达式中,遇到运算符则将其压入栈中,并将栈顶的两个操作数弹出进行运算后再将结果压入栈中。最后将栈中剩余的运算符依次弹出并输出到后缀表达式中即可。 对于中缀表达式,我们可以从左往右遍历,遇到操作数直接输出到后缀表达式中,遇到运算符则判断其与栈顶运算符的优先级,如果栈顶运算符的优先级高于或等于当前运算符,则弹出栈顶运算符并输出到后缀表达式中,直到栈为空或栈顶运算符的优先级低于当前运算符,然后将当前运算符压入栈中。最后将栈中剩余的运算符依次弹出并输出到后缀表达式中即可。 以下是 C 语言代码实现: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_STACK_SIZE 100 typedef struct stack { char data[MAX_STACK_SIZE]; int top; } Stack; void push(Stack *s, char c) { if (s->top == MAX_STACK_SIZE - 1) { printf("Stack overflow!\n"); exit(1); } s->data[++s->top] = c; } char pop(Stack *s) { if (s->top == -1) { printf("Stack underflow!\n"); exit(1); } return s->data[s->top--]; } int is_operator(char c) { return c == '+' || c == '-' || c == '*' || c == '/'; } int get_operator_priority(char c) { if (c == '*' || c == '/') { return 2; } else if (c == '+' || c == '-') { return 1; } else { return 0; } } void prefix_to_postfix(char *prefix, char *postfix) { Stack stack; stack.top = -1; int len = strlen(prefix); for (int i = len - 1; i >= 0; i--) { if (is_operator(prefix[i])) { char op1 = pop(&stack); char op2 = pop(&stack); postfix[strlen(postfix)] = op1; postfix[strlen(postfix)] = op2; postfix[strlen(postfix)] = prefix[i]; push(&stack, postfix[strlen(postfix) - 1]); } else { push(&stack, prefix[i]); } } while (stack.top != -1) { postfix[strlen(postfix)] = pop(&stack); } postfix[strlen(postfix)] = '\0'; } void infix_to_postfix(char *infix, char *postfix) { Stack stack; stack.top = -1; int len = strlen(infix); for (int i = 0; i < len; i++) { if (is_operator(infix[i])) { while (stack.top != -1 && get_operator_priority(stack.data[stack.top]) >= get_operator_priority(infix[i])) { postfix[strlen(postfix)] = pop(&stack); } push(&stack, infix[i]); } else if (infix[i] == '(') { push(&stack, infix[i]); } else if (infix[i] == ')') { while (stack.top != -1 && stack.data[stack.top] != '(') { postfix[strlen(postfix)] = pop(&stack); } if (stack.top == -1) { printf("Invalid expression!\n"); exit(1); } pop(&stack); } else { postfix[strlen(postfix)] = infix[i]; } } while (stack.top != -1) { if (stack.data[stack.top] == '(') { printf("Invalid expression!\n"); exit(1); } postfix[strlen(postfix)] = pop(&stack); } postfix[strlen(postfix)] = '\0'; } int main() { char expression[100], postfix[100] = ""; printf("Enter expression: "); gets(expression); infix_to_postfix(expression, postfix); printf("Postfix expression: %s", postfix); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值