-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsimplified_infix_to_posfix.c
94 lines (77 loc) · 1.91 KB
/
simplified_infix_to_posfix.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include "./utils/pilha.h"
#include <string.h>
#define MAXCOLS 80
bool isOperand(char c)
{
return isalnum(c);
}
int getPrecedence(char operator)
{
switch (operator)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default:
return 0;
}
}
bool hasPrecedence(char operator1, char operator2)
{
int precedence1 = getPrecedence(operator1);
int precedence2 = getPrecedence(operator2);
if (precedence1 == 0 && precedence2 == 0)
{
return false;
}
return precedence1 >= precedence2;
}
void infixToPosFix(char infix[], char posfix[]) {
Stack operatorStack;
operatorStack.top = -1;
int posfixLength = 0;
for (int i = 0; i < strlen(infix); i++) {
char symbol = infix[i];
if (isOperand(symbol)) {
posfix[posfixLength++] = symbol;
posfix[posfixLength++] = ' ';
} else {
while (!empty(&operatorStack) && hasPrecedence(operatorStack.items[operatorStack.top], symbol)) {
char topSymbol = pop(&operatorStack);
posfix[posfixLength++] = topSymbol;
posfix[posfixLength++] = ' ';
}
push(&operatorStack, symbol);
}
}
while (!empty(&operatorStack)) {
char topSymbol = pop(&operatorStack);
posfix[posfixLength++] = topSymbol;
posfix[posfixLength++] = ' ';
}
posfix[posfixLength] = '\0';
}
int main()
{
char infix[MAXCOLS];
char posfix[MAXCOLS];
printf("Digite a expressao infix: ");
fgets(infix, MAXCOLS, stdin);
char *pch = strchr(infix, ' ');
while (pch != NULL)
{
strncpy(pch, pch + 1, strlen(pch));
pch = strchr(infix, ' ');
}
infixToPosFix(infix, posfix);
printf("Expressao posfixa: %s\n", posfix);
return 0;
}