把一个把中缀表达式变成后缀表达式,有些情况可以运行正确结果,但是代码有bug,有一些情况不对。
代码如下
#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct Note)
struct Note
{
char date;
struct Note* next;
};
typedef struct Note* ptr;
typedef ptr Stack;
typedef ptr pos;
int isempty(Stack S);
int isempty(Stack S)
{
if(S->next==NULL)
{
return 0;
}
else
{
return 1;
}
}
char top(Stack S);
char top(Stack S)
{
if(isempty(S)!=0)
{
return S->next->date;
}
else
{
printf("空的");
return 0;
}
}
void pop(Stack S);
void pop(Stack S)
{
pos temp;
if(isempty(S)==0)
{
printf("空的");
}
else
{
temp=S->next;
S->next=S->next->next;
free(temp);
}
}
void Makeempty(Stack S);
void Makeempty(Stack S)
{
if(S==NULL)
{
printf("must use creatstack first");
}
else
{
while(isempty(S)!=0)
{
pop(S);
}
}
}
Stack creatStack(void);
Stack creatStack(void)
{
Stack S;
S=(struct Note*)malloc(sizeof(LEN));
if(S==NULL)
{
printf("out of space");
}
S->next=NULL;
Makeempty(S);
return S;
}
void push(char c,Stack S);
void push(char c,Stack S)
{
ptr temp;
temp=(struct Note*)malloc(LEN);
if(temp==NULL)
{
printf("out of space");
}
else
{
temp->date=c;
temp->next=S->next;
S->next=temp;
}
}
int main()
{
Stack S = creatStack();
char ch;
printf("请输入算式:");
while ((ch=getchar()) != '#')
{
if( ch>='0'&&ch<='9')
{
putchar(ch);
}
else if(ch=='+'||ch=='-')
{
if(isempty(S)==0)
{
push(ch,S);
}
else
{
do
{
if(top(S)=='(')
{
push(ch,S);
}
else
{
putchar(top(S));
pop(S);
push(ch,S);
}
}while( isempty(S)!=0 && top(S)== '(' );
if(top(S)!='(')
{
}
else
{
push(ch,S);
}
}
}
else if(ch==')')
{
while(top(S)!='(')
{
putchar(top(S));
pop(S);
}
pop(S);
}
/*乘、除、左括号都是优先级高的,直接压栈*/
else if(ch=='*'||ch=='/'||ch=='(')
{
push(ch,S);
}
}
while(isempty(S)!=0)
{
putchar(top(S));
pop(S);
}
return 0;
}
当输入9-62+3-(9/8)# 结果是9623+98/-- ,但是正确答案应该是962*-3+98/-