5
I am making a code that consists of analyzing an arithmetic expression, and checking if when I open a '(', then I must close a ')'. That is, check whether the expression is valid or not. For this I implemented a stack to help me solve this problem.
However, I realized that I should use a pointer pointer in my functions such as pop()
,push()
and verificasimbolo()
. However, it has not yet become clear to me why this implementation is taking place. Since in codes I implemented a simple chained list, in similar functions I only needed a pointer to make these changes.
Thank you for your attention.
Just follow my code:
#include <stdio.h>
#include <stdlib.h>
#define ABRE_PARENTESE '('
#define FECHA_PARENTESE ')'
struct pilha {
char elemento;
struct pilha* prox;
};
typedef struct pilha PILHA;
int ehvazia(PILHA** p) {
return *p == NULL;
}
void verifica(PILHA** p){
if(*p == NULL) {
printf("MEMORIA INDISPONIVEL\n");
exit(1);
}
}
void push(PILHA** topo, char newElemento) {
PILHA* newPtr = malloc(sizeof(PILHA));
verifica(&newPtr);
newPtr->elemento = newElemento;
newPtr->prox = (*topo);
(*topo) = newPtr;
printf("%c foi inserido na pilha.\n", (*topo)->elemento);
// free(newPtr);
}
void pop(PILHA** topo) {
PILHA* tempPtr;
tempPtr = malloc(sizeof(PILHA));
verifica(&tempPtr);
tempPtr = (*topo);
(*topo) = (*topo)->prox;
printf("%c foi removido da pilha.\n", tempPtr->elemento);
free(tempPtr);
}
void verificaSimbolo(PILHA** topo, char simbolo) {
if((simbolo == ABRE_PARENTESE)
|| (simbolo == FECHA_PARENTESE)) {
if(ehvazia(topo)) {
push(topo, simbolo);
}
else if(((*topo)->elemento == ABRE_PARENTESE)
&& (simbolo == FECHA_PARENTESE)){
pop(topo);
} else{
push(topo, simbolo);
}
}
}
int main(int argc, char** argv) {
PILHA* topo = NULL;
f
}
}
if(ehvazia(&topo))
printf("Expressao valida\n");
else
printf("Expressao invalida\n");
}
for(int i = 1; i < argc; i++) {
for(int j = 0; argv[i][j] != '\0'; j++) {
verificaSimbolo(&topo, argv[i][j]);
}
}
if(ehvazia(&topo))
printf("Expressao valida\n");
else
printf("Expressao invalida\n");
}
I understand now. Thank you very much Isac =)
– Otavio Augusto