后缀算法

时间:2019-03-20
本文章向大家介绍后缀算法,主要包括后缀算法使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

#include<iostream>
using namespace std;
#include<malloc.h>
#include<stdio.h>
#define MaxSize 50
typedef struct{
char data[MaxSize];
int top;
}A;
void InitStack(A *&L)
{
L=(A *)malloc(sizeof(A));
L->top=-1;
}
void DestoryStack(A *&L)
{
free(L);
}
bool StackEmpty(A *L)
{
return (L->top == -1);
}
bool Push(A *&L,char e)
{
if(L->top==MaxSize-1)
return false;
else
L->top++;
L->data[L->top]=e;
return true;
}
bool Pop(A *&L,char &e)
{
if(L->top==-1)
return false;
else
{
e=L->data[L->top];
L->top--;
return true;
}
}
bool GetTop(A *L,char &e)
{
if(L->top==-1)
return false;
else
{
e=L->data[L->top];
return true;
}
}
void trans(char *exp,char postexp[])
{
char e;
A *Optr;
InitStack(Optr);
int i = 0;
while(* exp!='\0')
{
switch(* exp)
{
case '(':
Push(Optr,'(');
exp++;
break;
case ')':
Pop(Optr,e);
while(e!='(')
{
postexp[i++]=e;
Pop(Optr,e);
}
exp++;
break;
case '+':
case '-':
while(!StackEmpty(Optr))
{
GetTop(Optr,e);
if(e!='(')
{
postexp[i++]=e;
Pop(Optr,e);
}
else
break;
}
Push(Optr,*exp);
exp++;
break;
case '*':
case '/':
while(!StackEmpty(Optr))
{
GetTop(Optr,e);
if(e=='*'||e=='/')
{
postexp[i++]=e;
Pop(Optr,e);
}
else
break;
}
Push(Optr,*exp);
exp++;
break;
default:
while(* exp>='A'&&*exp<='Z')
{
postexp[i++]=*exp;
exp++;
}
//postexp[i++]='#';
}
}
while(!StackEmpty(Optr))
{
Pop(Optr,e);
postexp[i++]=e;
}
postexp[i]='\0';
DestoryStack(Optr);
}
/*
void Display(char a[])
{
for(int i=0;a[i]!='#';i++)
{
cout<<a[i]<<endl;
}
}
*/
int main()
{
char exp[50],postexp[MaxSize];
char h;
for(int i=0;i<50;i++)
{
h=getchar();
if(h=='#')
{
exp[i]='\0';
break;
}
else
{
exp[i]=h;
}
}

trans(exp,postexp);
//Display(postexp);
printf("%s\n",postexp);
return 0;
}