堆栈数据结构(中缀到后缀)



这是一个在堆栈数据结构中将中缀转换为后缀的程序。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int F(char symbol)
{
switch(symbol)
{
case '+':
case '-':return 2;
case '*':
case '/':return 4;
case '^':
case '$':return 5;
case '(':return 0;
case '#':return -1;
default:return 8;
}
}
int G(char symbol)
{
switch(symbol)
{
case '+':
case '-':return 1;
case '*':
case '/':return 3;
case '^':
case '$':return 6;
case '(':return 9;
case ')':return 0;
default:return 7;
}
}
void infixtopostfix(char infix[],char postfix[])
{
int top,i,j=0;
top = -1;
char s[30],symbol;
s[++top]= '#';
for(i=0;i<strlen(infix);i++)
{
symbol = infix[i];
while(F(s[top]) > G(symbol))
{
postfix[j]=s[top--];
j++;
}
if(F(s[top]) != G(symbol))
s[++top]=symbol;
else
top--;
}
while(s[top] != '#')
{
postfix[j++]=s[top--];
}
postfix[j] = '';
}
int main()
{
char infix[20],postfix[20];
printf("Enter the infix expression:n");
scanf("%s",infix);
infixtopostfix(infix,postfix);
printf("Postfix Expression is %s",postfix);
return 0;
}

在这段代码中,下面的行是怎么回事?

if(F(s[top]) != G(symbol))
s[++top]=symbol;
else
top--;
}
while(s[top] != '#')
{
postfix[j++]=s[top--];
}

我不明白f(s[top]) != g(symbol)和f(s[top])>G(符号),因为如果它更大,就意味着它不相等。f(s[top])和g(symbol)是什么?

f(s[top]) != g(symbol)

f(s[top]) > g(symbol)

都是不同的

如果f(s[top])和g(symbol)相等,第一个给出false。但在第二种情况下,如果f(s[top])小于g(symbol),则生成false。但根据第一个条件,应该生成true。

最新更新