4
I’m making a code that converts an infix function to post-fixed notation, for example: 4+2 to 42+. And I’m not being able to prioritize the elements, for example, when I do the expression 4+2*8, I expect the result 428*+, but it’s printing 42*8+, because of the mathematical priority that is wrong in my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define max 1000
#include <stdbool.h>
typedef struct key{
char tipo;
}TipoItem;
typedef struct pilha{
TipoItem item[max];
int topo;
}Pilha;
void criapilha(Pilha *pi){
pi->topo=0;
}
void empilha(Pilha *pi,TipoItem c){
if(pi->topo == max){
printf("Pilha cheia.\n");
return;
}
else{
pi->item[pi->topo] = c;
pi->topo++;
}
}
int vazia(Pilha pi){
return (pi.topo == 0);
}
void desempilha(Pilha *pi,TipoItem *x){
char c;
if(vazia(*pi)){
//printf("Pilha vazia.\n");
return;
}
else{
*x = pi->item[pi->topo-1];
pi->topo--;
}
}
void printa(Pilha *pi){
if(pi->topo == 0){
printf("Pilha vazia.\n");
return;
}
else{
int i;
for(i=0;i<pi->topo;i++){
printf("%c ",pi->item[i]);
}
}
}
int prioridade(char a, char b){
if('a' <= 'c')
return 1;
else
return 0;
}
int main(){
Pilha pi; criapilha(&pi);
TipoItem elemento,pop;
char funcao[max];
int i,j=0;
int p = prioridade('a','b');
printf("%d",p);
scanf("%[^\n]",funcao);
for(i=0;i<strlen(funcao);i++){
elemento.tipo = funcao[i];
if(elemento.tipo == '-' || elemento.tipo == '+' || elemento.tipo == '/' || elemento.tipo == '^' || elemento.tipo == '*' || elemento.tipo == '(' || elemento.tipo == ')'){
if(pi.topo == 0 || elemento.tipo == '('){
empilha(&pi,elemento);
}
else if(pi.topo == 0 || elemento.tipo == ')'){
while(pi.topo>0 && pop.tipo!= '('){
printa(&pi);
desempilha(&pi,&pop);
}
desempilha(&pi,&pop);
}else{
while(pi.topo > 0){
printa(&pi);
desempilha(&pi,&pop);
}
empilha(&pi,elemento);
}
}else{
printf("%c",elemento.tipo);
}
}
//printf("%c",elemento.tipo);
while(pi.topo > 0){
printa(&pi);
desempilha(&pi,&pop);
}
return 0;
}
You need a function that returns the operator’s priority. Multiplication and division have higher priority than addition and subtraction, which in turn have higher priority than parentheses. The idea, when the operator is not
(
and)
, is to pop up the stack while the item priority at the top of the stack is higher than the current element priority. See that article (in English) with a Python solution. You are very close!– Anthony Accioly
Yeah, I’m trying, bro I’ve done about 10 jobs here and it didn’t work out to buy the stops.
– Pedro Henrique Faria Teixeira
I have the code here, almost ready, only it remains to compare the priorities when you do not need it does everything right, if you want to take a look at the code
– Pedro Henrique Faria Teixeira
Transfer all numbers and symbols to ASCII, put in order and crescent and transform back.
– user79236