SWUST OJ1042: 中缀表达式转换为后缀表达式

题目描述

中缀表达式是一个通用的算术或逻辑公式表示方法,操作符是以中缀形式处于操作数的中间(例:3 + 4),中缀表达式是人们常用的算术表示方法。后缀表达式不包含括号,运算符放在两个运算对象的后面,所有的计算按运算符出现的顺序,严格从左向右进行(不再考虑运算符的优先规则,如:(2 + 1) * 3 , 即2 1 + 3 *。利用栈结构,将中缀表达式转换为后缀表达式。(测试数据元素为单个字符)

输入

中缀表达式

输出

后缀表达式

样例输入

A+(B-C/D)*E

样例输出

ABCD/-E*+
#include<iostream>
#include<cstring>
#include<malloc.h>
using namespace std;
#define M 1000
typedef struct 
{
	char data[M];
	int top;
}stack;
void initstack(stack*&s)
{
	s=(stack*)malloc(sizeof(stack));
	s->top=-1;
}
void push(stack*&s,char a)
{
	s->top++;
	s->data[s->top]=a;
}
int empty(stack*s)
{
	if(s->top==-1)
	{
		return 0;
	}
	return 1;
}
char gettop(stack*s)
{
	return s->data[s->top];
}
void pop(stack*&s)
{
	s->top--;
}
int check(char a,char b)
{
	if((a=='+'||a=='-')&&(b=='*'||b=='/'))
	{
		return 1;
	}
	return 0;
} 
int main()
{
	stack*s;
	initstack(s);
	char str[M];
	cin>>str;
	int len=strlen(str);
	for(int i=0;i<len;i++)
	{
		if(str[i]!='('&&str[i]!='+'&&str[i]!='-'&&str[i]!='*'&&str[i]!='/'&&str[i]!=')')
		{
			cout<<str[i];
		}
		else if(str[i]=='(')
		{
			push(s,str[i]);
		}
		else
		{
			if(empty(s)==0||gettop(s)=='(')//0为栈空 
			{
				push(s,str[i]); 
			}
			else if(str[i]==')')//将(之后的全部弹出 
			{
				while(gettop(s)!='(')
				{
					cout<<gettop(s);
					pop(s);
				} 
				pop(s);//除( 
			}
			else
			{
				if(check(gettop(s),str[i])==1)//如果str[i]的优先级大于栈顶元素 
				{
					push(s,str[i]);
				}
				else
				{
					while(check(gettop(s),str[i])==1&&empty(s)==1)
					{
						cout<<gettop(s);
						pop(s);
					}
				}
			}
		}
	}
	while(empty(s)==1)
	{
		cout<<gettop(s);
		pop(s);
	}
	return 0;
}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值