#include<stdio.h>
#include<stdlib.h>
typedef struct SNode*Stack;
struct SNode{
char Data;
struct SNode*Next;
};
Stack CreateStack() //创建新堆栈节点
{
Stack S;
S=(Stack)malloc(sizeof(struct SNode));
S->Next=NULL;
return S;
}
void Push(Stack S,char c)
{
struct SNode*Temp;
Temp=(struct SNode*)malloc(sizeof(struct SNode));
Temp->Data=c;
Temp->Next=S->Next;
S->Next=Temp;
}
char Pop(Stack S)
{
struct SNode *FirstCell;
char TopData;
FirstCell=S->Next;
S->Next=FirstCell->Next;
TopData=FirstCell->Data ;
free(FirstCell);
return TopData;
}
char GetTop(Stack S)
{
return S->Next->Data;
}
char Precede(char c1,char c2) //判断运算符的优先级
{
char str[9] [9]={{"0+-*/()#"},
{"+>><<<>>"},
{"->><<<>>"} ,
{"*>>>><>>"},
{"/>>>><>>"},
{"(<<<<<=0"},
{")>>>>0>>"},
{"#<<<<<0="}};
int i,j,a,b;
for(i=0;c1!=str[0][i];i++);
a=i;
for(j=0;c2!=str[0][j];j++);
b=j;
return str[a][b];
}
bool In(char c) //判断是否为运算符
{
if(c=='+'||c=='-'||c=='*'||c=='/'||c=='('||c==')'||c=='#')
return true;
else
return false;
}
int main()
{
struct SNode *OPTR=CreateStack(); //堆栈存放运算符
struct SNode *OPND=CreateStack();
Push(OPTR,'#') ;
printf("请输入算式(完成后在算式末尾加上#)\n");
char c=getchar();
while(c!='#'||GetTop(OPTR)!='#')
{
if(!In(c)) //不是运算符进栈
{
Push(OPND,c);
c=getchar();
}
else
{
switch(Precede(GetTop(OPTR),c))
{
case'<':Push(OPTR,c);c=getchar();
break;
case'=': Pop(OPTR);
c=getchar();
break;
case'>':char temp=Pop(OPTR);
Push(OPND,temp);
break;
}
}
}
char b[20]={};
int j=0;
for(OPND;OPND->Next!=NULL;j++) //将堆栈中转换好的算式顺序倒置并输出
b[j]=Pop(OPND);
for(j;j>=0;j--)
printf("%c",b[j]);
return 0;
}
11-14
2011
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-29
3479
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)