学习数据结构的时候,在栈这节给出逆波兰式的运用,搜了下实现算法
// DataStructure.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
//#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<stack>
#include<math.h>
#include<string.h>
using namespace std;
#define max 100
char ex[max];/*存储后缀表达式*/
void trans()
{
/*将算术表达式转化为后缀表达式*/
printf("*****************************************\n");
printf("*输入一个求值的表达式,以#结束。*\n");
printf("******************************************\n");
printf("算数表达式:");
char str[max];/*存储原算术表达式*/
int charSum;
int i;
i=0;/*获取用户输入的表达式元素个数*/
do{
i++;
scanf("%c", &str[i]);
}while(str[i] != '#' && i != max);
charSum = i;
int t=1; //后缀表达式从1开始
char stack[max];/*作为运算符栈使用*/
int top = 0; //运算符栈顶
char ch;
i=1; //从1开始
ch = str[i];
while(ch != '#')
{
switch(ch)
{
case '(': /*判定为左括号,则放置运算符栈中*/
top++;
stack[top]=ch;
break;
case ')': /*判定为右括号,则将运算符栈中两括号之间内容放置到后缀表达式中*/
while(stack[top] != '(')
{
ex[t] = stack[top];
top--;
t++;
}
top--; //去除'('
break;
case '+': /*判定为加减号,肯定小于等于栈顶元素*/
case '-':
while(top !=0 && stack[top] != '(')
{
ex[t] = stack[top];
top--;
t++;
}
top++; //增加本身
stack[top]=ch;
break;
case '*': /*判定为乘除号,只会小于等于栈顶非乘除号*/
case '/':
while(stack[top] == '*' || stack[top] == '/')
{
ex[t]=stack[top];
top--;
t++;
}
top++; //增加本身
stack[top]=ch;
break;
case ' ':break; //空格排除
default: /*判定为数字*/
while(ch>='0'&& ch <= '9')
{
ex[t]=ch;
t++;
i++;
ch=str[i];
}
//常规下这里是数字,那么最后导致多加了一次i
i--;
ex[t] = ' '; //数字后置空格
t++;
}
i++; //下一个字符
ch = str[i];
}
while(top!=0)
{
ex[t]=stack[top];
t++;
top--;
}
ex[t]=' ';
printf("\n\t原来表达式:");
int j = 0;
for(j=1;j<charSum;j++)
printf("%c", str[j]);
printf("\n\t逆波兰式:", ex);
for(j=1;j<t;j++)
printf("%c",ex[j]);
printf("\n");
}
void compvalue()
{
/*计算后缀表达式的值*/
float stack[max],d;/*作为栈使用*/
char ch;
int t=1,top=0;/*t为ex下标,top为stack下标*/
ch=ex[t];t++;
while(ch != ' ')
{
switch(ch)
{
case '+':
stack[top-1]=stack[top-1]+stack[top];
top--;
break;
case '-':
stack[top-1]=stack[top-1]-stack[top];
top--;
break;
case '*':
stack[top-1]=stack[top-1]*stack[top];
top--;
break;
case '/':
if(stack[top] !=0 )
{
stack[top-1] = stack[top-1] / stack[top];
}
else
{
printf("\n\t除零错误!\n");
return;/*异常退出*/
}
top--;
break;
default:
d=0;
while(ch >= '0' && ch <= '9')
{
d = 10*d + ch - '0';/*将数字字符转化为对应的数值*/
ch = ex[t];
t++;
}
top++;
stack[top]=d;
}
ch = ex[t];
t++;
}
printf("\n\t计算结果:%g\n",stack[top]);
}
int _tmain(int argc, _TCHAR* argv[])
{
trans();
compvalue();
system("pause");
return 0;
}