中缀表达式求值(C/C++语言实现)

       中缀表达式求值是数据结构中栈的应用的一个典型,要学会使用C/C++语言书写中缀表达式求值并不难,关键在于方法得当(分析栈内外运算符的优先级)。

       下面,我会将中缀表达式求值的代码模板呈现,同学们可以通过代码自行传递参数,分析计算机运行代码的每一步,进而达到熟悉计算机进行中缀表达式求值的步骤,以及熟练堆栈应用操作的目的。

       代码中,我将中缀表达式求值的思路分为了两部分,首先要将中缀表达式转化为后缀表达式,然后再对后缀表达式求值。

#include <iostream>
#include <stack>
#include <string.h>

using namespace std;

int isp(char ch); // 栈内运算符优先级 
int icp(char ch); // 栈外运算符优先级 
char *InToPost(char *InString, int L); // 中缀表达式转后缀表达式 

int PostExpEvaluation(char *str);// 后缀表达式求值 

int main() {
	char str[110];
	gets(str);
	int L = strlen(str);
	strcpy(str, InToPost(str, L)); // 获得中缀表达式的后缀表达式 
	cout << PostExpEvaluation(str) << endl; // 后缀表达式求值 
	return 0;
}

int PostExpEvaluation(char *str) {
	stack<int> s;
	int x, y;
	for(int i = 0; str[i] != '\0'; ++i)
	{
		if(str[i] != '+' && str[i] != '-' && str[i] != '*' && str[i] != '/') {// 如果不为运算符则运算数入栈 
			s.push(str[i] - '0');
		}
		else {// 栈中弹出两个运算符x、y才能运算,运算结果入栈
			y = s.top();
			s.pop();
			if(s.empty()) {
				cout << "Expression Error: " << y << endl; // 非正常终止,表达式有误 
				exit(0);
			}
			switch (str[i]) {
				case '+': 
					x = s.top();
					s.pop();
					s.push(x+y);
					break;
				case '-':
					x = s.top();
					s.pop();
					s.push(x-y);
					break;
				case '*':
					x = s.top();
					s.pop();
					s.push(x*y);
					break;
				case '/':
					if(y == 0) {
						cout << "Error: " << y << "/0" << endl;// 非正常终止,除数为0 
						exit(0);
					}
					x = s.top();
					s.pop();
					s.push(x / y);
					break;
			}
		}
	}
	x = s.top(); // 栈中仅剩的元素为最终结果 
	s.pop();
	return x;
}

char *InToPost(char *InString, int L) {
	stack<char> s;
	int i = 0, j = 0;
	char PostString[110];
	s.push('#');
	while(i < L) {
		if(InString[i] != '#' && InString[i] != '+' && InString[i] != '-' && InString[i] != '*' && InString[i] != '/' && InString[i] != '(' && InString[i] != ')') {
			PostString[j++] = InString[i++]; // 如果当前中缀表达式字符是操作数,则直接输出在后缀表达式中 
		}
		else 
		{
			if(isp(s.top()) < icp(InString[i])) {// 如果栈顶运算符优先级小于栈外运算符优先级,则栈外运算符入栈,i++
				s.push(InString[i++]);
			}
			else if(isp(s.top()) == icp(InString[i])) {// 如果栈顶运算符优先级等于栈外运算符优先级,则栈顶运算符直接出栈,i++
				s.pop(); i++;
			}
			else {
				PostString[j++] = s.top();// 如果栈顶运算符优先级大于栈外运算符优先级,则栈顶运算符输出在后缀表达式并出栈 
				s.pop();
			}
		}
	}
	static char str[110]; // static定义变量在程序结束才释放内存,return返回static不会有警告 
	strcpy(str, PostString);// PostString是局部变量,函数调用结束后内存销毁,直接返回会警告出错 
	return str;
}

int isp(char ch) {
	if(ch == '(')
	return 1;
	else if(ch == ')')
	return 6;
	else if(ch == '+')
	return 3;
	else if(ch == '-')
	return 3;
	else if(ch == '*')
	return 5;
	else if(ch == '/')
	return 5;
	else if(ch == '#')
	return 0;
}

int icp(char ch) {
	if(ch == '(')
	return 6;
	else if(ch == ')')
	return 1;
	else if(ch == '+')
	return 2;
	else if(ch == '-')
	return 2;
	else if(ch == '*')
	return 4;
	else if(ch == '/')
	return 4;
	else if(ch == '#')
	return 0;
}

切记!!!输入中缀表达式末尾要有#

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
下面是一种用C语言实现中缀表达式求值算法: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define MAX_SIZE 100 typedef struct Stack { int top; int data[MAX_SIZE]; } Stack; int is_empty(Stack *s) { return s->top == -1; } int is_full(Stack *s) { return s->top == MAX_SIZE - 1; } void push(Stack *s, int value) { if (is_full(s)) { printf("Stack is full.\n"); exit(1); } s->top++; s->data[s->top] = value; } int pop(Stack *s) { if (is_empty(s)) { printf("Stack is empty.\n"); exit(1); } int value = s->data[s->top]; s->top--; return value; } int peek(Stack *s) { if (is_empty(s)) { printf("Stack is empty.\n"); exit(1); } return s->data[s->top]; } int priority(char op) { switch (op) { case '+': case '-': return 1; case '*': case '/': return 2; default: return 0; } } int evaluate(int op1, int op2, char op) { switch (op) { case '+': return op1 + op2; case '-': return op1 - op2; case '*': return op1 * op2; case '/': return op1 / op2; default: return 0; } } int infix_to_postfix(char *infix, char *postfix) { int i, j; Stack s; s.top = -1; for (i = 0, j = 0; infix[i] != '\0'; i++) { if (isdigit(infix[i])) { postfix[j++] = infix[i]; } else if (infix[i] == '(') { push(&s, infix[i]); } else if (infix[i] == ')') { while (!is_empty(&s) && peek(&s) != '(') { postfix[j++] = pop(&s); } if (is_empty(&s)) { printf("Invalid expression.\n"); exit(1); } pop(&s); } else if (infix[i] == '+' || infix[i] == '-' || infix[i] == '*' || infix[i] == '/') { while (!is_empty(&s) && peek(&s) != '(' && priority(infix[i]) <= priority(peek(&s))) { postfix[j++] = pop(&s); } push(&s, infix[i]); } else { printf("Invalid character: %c\n", infix[i]); exit(1); } } while (!is_empty(&s)) { if (peek(&s) == '(') { printf("Invalid expression.\n"); exit(1); } postfix[j++] = pop(&s); } postfix[j] = '\0'; return j; } int evaluate_postfix(char *postfix) { int i; Stack s; s.top = -1; for (i = 0; postfix[i] != '\0'; i++) { if (isdigit(postfix[i])) { push(&s, postfix[i] - '0'); } else if (postfix[i] == '+' || postfix[i] == '-' || postfix[i] == '*' || postfix[i] == '/') { int op2 = pop(&s); int op1 = pop(&s); int result = evaluate(op1, op2, postfix[i]); push(&s, result); } else { printf("Invalid character: %c\n", postfix[i]); exit(1); } } if (s.top != 0) { printf("Invalid expression.\n"); exit(1); } return pop(&s); } int main() { char infix[MAX_SIZE], postfix[MAX_SIZE]; printf("Enter an infix expression: "); fgets(infix, MAX_SIZE, stdin); infix[strcspn(infix, "\n")] = '\0'; int length = infix_to_postfix(infix, postfix); printf("Postfix expression: %s\n", postfix); int result = evaluate_postfix(postfix); printf("Result: %d\n", result); return 0; } ``` 该算法使用两个栈,一个用于转换中缀表达式为后缀表达式,另一个用于求解后缀表达式。其中,转换中缀表达式为后缀表达式的过程中,遇到操作数直接输出到后缀表达式中,遇到左括号直接压入栈中,遇到右括号则将栈中元素弹出直到遇到左括号,并将左右括号都丢弃。遇到操作符时,如果栈顶元素为左括号,则直接将操作符压入栈中;否则,将栈中优先级大于等于当前操作符的元素都弹出,直到栈为空或栈顶元素为左括号,并将当前操作符压入栈中。转换完成后,如果栈中还有元素,则依次弹出并输出到后缀表达式中。 求解后缀表达式的过程中,遇到操作数则直接压入栈中,遇到操作符则弹出栈顶的两个元素作为操作数,计算结果并将结果压入栈中。最终,如果栈中只有一个元素,则该元素即为表达式的值。如果栈中元素多于一个,则表明表达式有误。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值