#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);
}
数学运算后缀表达式转换成中缀表达式
栈队列实现表达式转换
最新推荐文章于 2024-09-12 17:28:58 发布
本文介绍如何使用栈和循环队列实现中缀表达式到后缀表达式的转换过程。通过定义相应的数据结构和算法步骤,实现了有效的表达式转换,并展示了完整的C++代码实现。
1684

被折叠的 条评论
为什么被折叠?



