中缀表达式转后缀表达式C++代码

//MyStack.h

#include <iostream>
using namespace std;

template <class ElemType> class MyStack
{
public:
	const static  int MAXSIZE =100;
	ElemType data[MAXSIZE];
	int top;

public:
	void init();			// 初始化栈
	bool empty();			// 判断栈是否为空
	ElemType gettop();	    // 读取栈顶元素(不出栈)
	void push(ElemType x);	// 进栈
	ElemType pop();			// 出栈
};


template<class T> void MyStack<T>::init()
{
	this->top = 0;
}

template<class T> bool MyStack<T>::empty()
{
	return this->top == 0? true : false;
}

template<class T> T MyStack<T>::gettop()
{
	if(empty())
	{
		cout << "栈为空!\n";
		exit(1);
	}
	return this->data[this->top-1];
}

template<class T> void MyStack<T>::push(T x)
{
	if(this->top == MAXSIZE)
	{
		cout << "栈已满!\n";
		exit(1);
	}
	this->data[this->top] =x;
	this->top ++;
}

template<class T> T MyStack<T>::pop()
{
	if(this->empty())
	{
		cout << "栈为空! \n";
		exit(1);
	}

	T e =this->data[this->top-1];
	this->top --;
	return e;
}


// PrefixToPostfix.h

#include <vector>
using namespace std;

bool isoperator(char op);						  // 判断是否为运算符
int priority(char op);						  	  // 求运算符优先级
void postfix(char pre[] , char post[],int &n);    // 把中缀表达式转换为后缀表达式
double read_number(char str[],int *i);			  // 将数字字符串转变成相应的数字
double postfix_value(char post[]);				  // 由后缀表达式字符串计算相应的中值表达式的值	

// PrefixToPostfix.cpp

#include "MyStack.h"
#include "PrefixToPostfix.h"

#include <iostream>
using namespace std;

void main()
{
	MyStack<int> stack ;
	stack.init();

	//char pre[] ="22/(5*2+1)#";
	char exp[100];
	cout << "输入表达式(中缀,以#结束):";
	cin >> exp;

	char post[100] ;
	//cout <<"中缀表达式为:"<< pre << endl;

	int n =0;			// 返回后缀表达式的长度
	postfix(exp,post,n);
	cout <<"后缀表达式为:";
	for( int i =0 ;i < n ;i++)
		cout << post[i] ;

	cout << "\n由后缀表达式计算出的数值结果:  ";
	cout << postfix_value(post) << endl;

	system("pause");
}

bool isoperator(char op)
{
	switch(op)
	{
	case '+':
	case '-':
	case '*':
	case '/':
		return 1;
	default : 
		return 0;
	}
}


int priority(char op)
{
	switch(op)
	{
	case '#':
		return -1;
	case '(':
		return 0;
	case '+':
	case '-':
		return 1;
	case '*':
	case '/':
		return 2;
	default :
		return -1;
	}
}

//	 把中缀表达式转换为后缀表达式,返回后缀表达式的长度(包括空格)
void postfix(char pre[] ,char post[],int &n)
{
	int i = 0 ,j=0;
	MyStack<char> stack;
	stack.init();		// 初始化存储操作符的栈

	stack.push('#');	// 首先把结束标志‘#’放入栈底

	while(pre[i]!='#')
	{
		if((pre[i]>='0' && pre[i] <='9')||pre[i] =='.') // 遇到数字和小数点直接写入后缀表达式
		{
			post[j++] = pre[i];
			n++;
		}
		else if (pre[i]=='(')	// 遇到“(”不用比较直接入栈
			stack.push(pre[i]);
		else if(pre[i] ==')')  // 遇到右括号将其对应左括号后的操作符(操作符栈中的)全部写入后缀表达式
		{
			while(stack.gettop()!='(')
			{
				post[j++] = stack.pop();
				n++;
			}
			stack.pop(); // 将“(”出栈,后缀表达式中不含小括号
		}
		else if (isoperator(pre[i]))
		{
			post[j++] = ' '; // 用空格分开操作数(
			n++;
			while(priority(pre[i]) <= priority(stack.gettop())) 
			{
				// 当前的操作符小于等于栈顶操作符的优先级时,将栈顶操作符写入到后缀表达式,重复此过程
				post[j++] = stack.pop();
				n++;
			}

			stack.push(pre[i]);	// 当前操作符优先级大于栈顶操作符的优先级,将该操作符入栈
		}

		i++;
	}
	while(stack.top) // 将所有的操作符加入后缀表达式
	{
		post[j++] = stack.pop();
		n++;
	}
}

double read_number(char str[],int *i)
{
	double x=0.0;
	int k = 0;
	while(str[*i] >='0' && str[*i]<='9')  // 处理整数部分
	{
		x = x*10+(str[*i]-'0');
		(*i)++;
	}

	if(str[*i]=='.') // 处理小数部分
	{
		(*i)++;
		while(str[*i] >= '0'&&str[*i] <='9')
		{
			x = x * 10 + (str[*i]-'0');
			(*i)++;
			k++;
		}
	}
	while(k!=0)
	{
		x /= 10.0;
		k--;
	}

	return x;
}

double postfix_value(char post[])
{
	MyStack<double> stack;	// 操作数栈
	stack.init();

	int i=0 ;
	double x1,x2;

	while(post[i] !='#')
	{
		if(post[i] >='0' && post[i] <='9')
			stack.push(read_number(post,&i));
		else if(post[i] == ' ')
			i++;
		else if (post[i] =='+')
		{
			x2 = stack.pop();
			x1 = stack.pop();
			stack.push(x1+x2);
			i++;
		}
		else if (post[i] =='-')
		{
			x2 = stack.pop();
			x1 = stack.pop();
			stack.push(x1-x2);
			i++;
		}
		else if (post[i] =='*')
		{
			x2 = stack.pop();
			x1 = stack.pop();
			stack.push(x1*x2);
			i++;
		}
		else if (post[i] =='/')
		{
			x2 = stack.pop();
			x1 = stack.pop();
			stack.push(x1/x2);
			i++;
		}
	}
	return stack.gettop();
}


运行结果:



其实现原理见<栈的应用--计算表达式>,http://blog.csdn.net/swkiller/article/details/6829465

  • 7
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
我可以回答您的问题,以下是将中缀表达式转换后缀表达式的C代码示例: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #define SIZE 100 char stack[SIZE]; int top = -1; void push(char item) { if (top >= SIZE - 1) { printf("\nStack Overflow."); } else { top = top + 1; stack[top] = item; } } char pop() { char item; if (top < 0) { printf("stack under flow: invalid infix expression"); getchar(); exit(1); } else { item = stack[top]; top = top - 1; return (item); } } int is_operator(char symbol) { if (symbol == '^' || symbol == '*' || symbol == '/' || symbol == '+' || symbol == '-') { return 1; } else { return 0; } } int precedence(char symbol) { if (symbol == '^') { return (3); } else if (symbol == '*' || symbol == '/') { return (2); } else if (symbol == '+' || symbol == '-') { return (1); } else { return (0); } } void infix_to_postfix(char infix_exp[], char postfix_exp[]) { int i, j; char item; char x; push('('); strcat(infix_exp, ")"); i = 0; j = 0; item = infix_exp[i]; while (item != '\0') { if (item == '(') { push(item); } else if (isdigit(item) || isalpha(item)) { postfix_exp[j] = item; j++; } else if (is_operator(item) == 1) { x = pop(); while (is_operator(x) == 1 && precedence(x) >= precedence(item)) { postfix_exp[j] = x; j++; x = pop(); } push(x); push(item); } else if (item == ')') { x = pop(); while (x != '(') { postfix_exp[j] = x; j++; x = pop(); } } else { printf("\nInvalid infix Expression.\n"); getchar(); exit(1); } i++; item = infix_exp[i]; } if (top > 0) { printf("\nInvalid infix Expression.\n"); getchar(); exit(1); } postfix_exp[j] = '\0'; } int main() { char infix[SIZE], postfix[SIZE]; printf("Enter Infix expression : "); gets_s(infix); infix_to_postfix(infix, postfix); printf("Postfix Expression: "); puts(postfix); return 0; } ``` 希望这能帮助您。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值