最近在回顾学期刚开始看的浙大的数据结构慕课,想把中缀表达式转后缀表达式的代码打出来,发现网上很多的代码在乘号和除号的处理都不太正确,我参考课件把代码打了一遍,改了很久,有不对的地方希望大家指出。
基本思路见浙大慕课的PPT:
具体算法实现如下:(我把转化部分写在主函数了)
#include
#include
#define ElemType char
typedef struct SNode *Stack;
struct SNode
{
ElemType data;
struct SNode *next;
};
Stack Create()
{
Stack s=(Stack)malloc(sizeof(struct SNode));
s->next=NULL;
return s;
}
int IsEmpty(Stack s)
{
return (s->next==NULL);
}
Stack Push(Stack s,ElemType x)
{
Stack temp=(Stack)malloc(sizeof(struct SNode));
temp->data=x;
temp->next=s->next;
s->next=temp;
return s;
}
ElemType Pop(Stack s)
{
if(s->next==NULL)
{
printf("stack is empty.\n");
return NULL;
}
else
{
struct SNode *first=s->next;
s->next=first->next;
ElemType firstElem=first->data;
free(first);
return firstElem;
}
}
int main()
{
Stack s=Create();
char c,e;
printf("请输入中缀表达式,以#作为结束标志:\n");
scanf("%c",&c);
while(c!='#')
{
while(c>='0'&& c<='9')
{
putchar(c);
scanf("%c",&c);
if(c<'0'||c>'9')
putchar(' ');
}
if(c=='(')
Push(s,c);
else if(c==')')
{
e=Pop(s);
while(e!='(')
{
putchar(e);
e=Pop(s);
}
}
else if(c=='+'||c=='-')
{
if(IsEmpty(s))
Push(s,c);
else
{
do
{
e=Pop(s);
if(e=='(')
Push(s,e);
else
{
putchar(e);
}
}while(!IsEmpty(s)&&e!='(');
Push(s,c);
}
}
else if(c=='*'||c=='/')
{
if(IsEmpty(s))
Push(s,c);
else
{
e=Pop(s);
if(e=='+'||e=='-'||e=='(')
Push(s,e);
while(e!='+' && e!='-' && e!='(')
{
putchar(e);
if(!IsEmpty(s))
e=Pop(s);
else
break;
}
Push(s,c);
}
}
else if(c=='#')
break;
scanf("%c",&c);
}
while(!IsEmpty(s))
{
e=Pop(s);
putchar(e);
}
return 0;
}