数据结构-中缀式转后缀式-C语言实现
#include<stdio.h>
#include<stdlib.h>
int length(char String[]) {
int count = 0;
for (int i = 0; String[i] != '\0'; i++)
count++;
return count;
}
void after(char String[]) {
int len = length(String);
char stack[19];
char ch[6] = { '+','-','*','/','(',')' };
int top = -1;
for (int i = 0; i < len; i++) {
int flag = 0;
for (int j = 0; j < 6; j++) {
if (String[i] == ch[j]) {
flag = 1;
break;
}
}
if (flag == 0) {
printf("%c", String[i]);
continue;
}
else {
if (String[i] == ')') {
for (; stack[top] != '('; top--) {
printf("%c", stack[top]);
}
top--;
continue;
}
if (top == -1 || String[i] == '(') {
stack[++top] = String[i];
continue;
}
else {
if (stack[top] == '(') {
stack[++top] = String[i];
continue;
}
int pr, pp;
if (String[i] == '+' || String[i] == '-') {
pr = 0;
}
if (String[i] == '*' || String[i] == '/') {
pr = 1;
}
if (stack[top] == '+' || stack[top] == '-') {
pp = 0;
}
if (stack[top] == '*' || stack[top] == '/') {
pp = 1;
}
if (pr <= pp) {
int cc = 0;
for (int j = 0; j <=top; j++)
if (stack[j] == '(') {
cc = 1; break;
}
if (cc == 1) {
for (; stack[top] != '('; top--)
printf("%c", stack[top]);
}
else
{
for (; top >= 0; top--)
printf("%c", stack[top]);
}
stack[++top] = String[i];
}
else {
stack[++top] = String[i];
}
}
}
}
for (; top != -1; top--) {
printf("%c", stack[top]);
}
}
void main()
{
char String[] = "a+b-a*((c+d)/e-f)+g";
after(String);
}
|