数学运算后缀表达式转换成中缀表达式

#include <string.h> 
#include <iostream.h> 
#include <stdlib.h> 

#define MaxSize 32 

typedef char Qelemtype; 

typedef struct 
{ 
Qelemtype *base; //指向队列的存储空间; 
int front; //指向队头元素; 
int rear; //指向队尾元素的下一位置; 
}SqQueue; 

typedef struct LNode 
{ 
int data; 
struct LNode *next; 
}Snode,*LinkStack; 


void DestroyLinStack(LinkStack &S) 
{//销毁链栈S。 
LinkStack temp=S,p; 
while(temp) 
{ 
p=temp; 
temp=temp->next; 
free(p); 
} 
} 

void Push(LinkStack &S, char x) 
{//入栈。 
LinkStack temp=(LinkStack )malloc(sizeof(Snode )); 
temp->data=x; 
temp->next=S->next; 
S->next=temp; 
} 

void Pop(LinkStack &S, char &x) 
{//出栈。 
LinkStack temp=S->next; 
x=temp->data; 
S->next=temp->next; 
free(temp); 
} 

int GetTop(LinkStack &S) 
{//读栈顶元素. 
int x; 
if(S->next) 
x=S->next->data; 
else 
cout<<"Stack Null "<<endl; 
return x; 

} 

void Initstack(LinkStack &S) 
{ 
S=(LinkStack )malloc(sizeof(Snode )); 
if(!S) 
{ 
cout<<"Alloctation Error"<<endl; 
exit(1); 
} 
S->next=0; 
} 


int InitQueue(SqQueue &Q) 
{//队列的初始化; 
Q.front=Q.rear=0; 
Q.base=(Qelemtype *)malloc(MaxSize*sizeof(Qelemtype)); 
if(!Q.base) 
exit(1); 
Q.base[Q.front]='\0'; 
return 1; 
} 

int QueueLength(SqQueue Q) 
{//计算队列的长度; 
return (Q.rear-Q.front+MaxSize)%MaxSize; 
} 

void EnQueue(SqQueue &Q, Qelemtype x) 
{//入队; 
if(QueueLength(Q)==MaxSize) 
{ 
cout<<"EnQueue Error "<<endl; 
return ; 
} 
Q.base[Q.rear++]=x; 
} 


void DispQueue(SqQueue Q) 
{//输出队列的所有元素; 
int i=0,j=Q.front; 
while(i<QueueLength(Q)) 
{ 
cout<<Q.base[j]; 
j++; 
i++; 
} 
} 

void DestroyQueue(SqQueue &Q) 
{ 
//队列的销毁; 
delete []Q.base; 
Q.base=0; 
Q.front=Q.rear=0; 
return ; 
} 


int StackEmpty(LinkStack S) 
{//判断栈是否为空. 
return (S->next==0); 
} 

int Priority(char oper) 
{ 
switch(oper) 
{ 
case '(': 
return 0; 
case '+': 
case '-': 
return 1; 
case '*': 
case '/': 
return 2; 
} 
} 

void convertpostexp(char *str,SqQueue &post) 
{ 
char c,t; 
int i=0,k=strlen(str); 
LinkStack S; 
Initstack(S); 
Push(S,'('); 
InitQueue(post); 
while(i<k || !StackEmpty(S)) 
{ 
c=*str++; 
switch(c) 
{ 
case '0': 
case '1': 
case '2': 
case '3': 
case '4': 
case '5': 
case '6': 
case '7': 
case '8': 
case '9': 
EnQueue(post, c); 
break; 
case '(': 
Push(S,c); 
break; 
case ')': 
case ';': 
do{ 
Pop(S,t); 
if(t!='(') 
EnQueue(post, t); 
}while(t!='(' && !StackEmpty(S)); 
break; 
case '+': 
case '-': 
case '*': 
case '/': 
while(Priority(c)<=Priority(GetTop(S))) 
{ 
Pop(S,t); 
EnQueue(post, t); 
} 
Push(S,c); 
break; 
} 
i++; 
} 
DestroyLinStack(S); 
} 


void main() 
{ 
SqQueue post; 
char str[32]; 
cout<<"请输入计算表达式:(在最后要加上;)"<<endl; 
cin>>str; 
convertpostexp(str,post); 
cout<<"转换成后缀表达式是:"<<endl; 
DispQueue(post); 
cout<<endl; 
DestroyQueue(post); 
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值