data-structures - 堆栈数据结构(后缀的中缀)
问题描述
这是一个将堆栈数据结构中的中缀转换为后缀的程序。
#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] = '\0';
}
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(symbol) 有何不同,因为如果它更大,则自动意味着它不相等。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。
推荐阅读
- javascript - 一个函数中有多个事件处理程序
- elixir - JSON 响应的单元测试,匹配 JSON 响应以断言键和值
- r - 在库函数中分配变量
- angular - Angular 6.x 元标记 OG:描述不适用于 FB
- unit-testing - Rails 升级后的神秘 rspec 错误
- javascript - 如何使用 JS 动态创建 SVG 文本元素
- python - 处理的 python 是固定在一个 CPU 上,还是可以使用多个 CPU 超时?
- python-3.x - 为 pyinstaller 使用了 pip,但 pyinstaller 仍然无法识别
- python - 使用 Python 的 AdaDelta 优化算法
- cratedb - 如何在 CrateDB SQL 查询中减去时间戳的天数?