通过中缀表达式求逆波兰表达式 ## 逆波兰式

本文介绍了如何将中缀表达式转换为逆波兰表达式的方法,利用运算符栈,根据运算符的优先级进行处理。在遇到操作数时直接输出,遇到高优先级运算符则进栈,遇到低优先级运算符则连续弹出栈顶运算符。括号用于调整运算顺序,右括号标志着子表达式的结束。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 设立暂存运算符的栈;
  2. 设表达式的结束符为“#”,
    予设运算符栈的栈底为“#”
  3. 若当前字符是操作数,
    则直接发送给后缀式;
  4. 若当前表达式运算符的优先数高于栈顶运算符,则进栈;
  5. 否则,退出栈顶运算符发送给后缀式;
  6. “(” 对它前后的运算符起隔离作用,
    “)”可视为自相应左括弧开始的表达式的结束符
#include <iostream>
#include <stdio.h>
#include <map>
#include <string>

#define STACK_INIT_SIZE 100
#define BUFFER_LENGTH 100
#define OK 1
#define ERROR -1
typedef char ElemType;
typedef int Status;

using namespace std;
map<char, int> GetPriority;

typedef struct {
	ElemType *base;
	ElemType *top;
	int stacksize;
} SqStack;

Status InitStack(SqStack &S)
{
	S.base = new ElemType[STACK_INIT_SIZE];
	if (!S.base) exit(OVERFLOW);
	S.top = S.base;
	S.stacksize = STACK_INIT_SIZE;
	return OK;
}

Status Push(SqStack &S, ElemType e)
{
	if (S.top - S.base >= S.stacksize)
		return OVERFLOW;
	S.top++;
	*S.top = e;
	return OK;
}

Status Pop(SqStack &S)
{
	if (S.top == S.base) return ERROR;
	S.top--;
	return OK;
}

void RecurvePop(SqStack &S, ElemType e,string &s)
{
	int topprior = GetPriority[*S.top];
	int prior = GetPriority[e];
	if (topprior > prior ) return;
	s += *S.top;
	Pop(S);
	RecurvePop(S, e,s);
	
}

bool StackEmpty(const SqStack &S)
{
	if (S.top == S.base) return true;
	else return false;
}

string TransformRPN(char exp[],int len)
{
	string s;
	SqStack S;
	InitStack(S); Push(S, '#');

	for (int i = 0; i < len; i++)
	{
		char ch = exp[i];
		int prio = GetPriority[ch];
		if (prio == 0)
			s += ch;
		else {
			if (prio == GetPriority['('])
				Push(S, ch);
			else if (prio == GetPriority[')']){
				RecurvePop(S, ch,s);
				Pop(S);
			}
			else {
				int topprio = GetPriority[*S.top];
				//先判断top的优先级比现在这个操作符高还是低
				 if (prio >= topprio)
					RecurvePop(S, ch,s);
				Push(S, ch);
			}
		}
	}
	RecurvePop(S, '?', s);
	return s;
}

void InitMap()
{
	
	//读入操作符ch,如果栈顶的元素top即上一个操作符的优先级比ch低或相等,就输出top,递归,直到碰到优先级比ch高的;
	//如果栈顶的元素top即上一个操作符的优先级比ch高,那就把ch Push到栈上去;
	GetPriority['*'] = 2; GetPriority['/'] = 2;
	GetPriority['+'] = 3; GetPriority['-'] = 3;
	GetPriority[')'] = 4; GetPriority['('] = 5;
	GetPriority['?'] = 7;//结束之后通过递归全部pop
	GetPriority['#'] = 8;//Stack最底层的,确保Pop不出界
}

int main()
{
	InitMap();

	char buffer[BUFFER_LENGTH];
	cin >> buffer;
	
	 cout << TransformRPN(buffer, strlen(buffer));

	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值