1
Good night, you guys!
I’m trying to do a 2011 OBI exercise. Here’s the link to it: Exercise OBI 2011- Expressions and found some problems to accomplish it.
In short, the exercise provides you with a string: {[(}]) and you need to tell whether they are 'balanced' or not.
Example of balanced chains: {},{[]}, ([{}]).
Example of unbalanced chains, }{, [{}}, [}.
I thought of using a stack that counts the number of "[, { e (" you find to push (in this case, increase the stack with the last [, {, or ( found). And after that, go comparing to see if the rest of the string has the opposite characters to the top of the stack. So, if at the top it’s '{', it looks for '}' and finds it, it removes it from the stack. In the end, if there are elements left in the stack, it means that the string is not balanced.
Follows my implementation:
Main:
int main()
{
//Numero de instancias
int T;
scanf("%d", &T);
int i;
char* exp;
for( i = 0; i < T; i++)
{
scanf("%s", exp);
if(validaCadeia(exp) == 0)
printf("S\n");
else
printf("N\n");
}
return(0);
}
In main, I take the amount of expressions that the user wants to perform(T), and I make a request for the string and calling the function that checks if they are balanced.
The function:
int validaCadeia(char* cadeia)
{
int i = 0;
//declara o Nó cabeça, ou topo
/*Declaração da pilha e de suas variaveis.*/
Pilha* p = (Pilha*)malloc(sizeof(Pilha));
if(!p)
return(0);
//Inicia a pilha como vazia
p->topo = NULL;
while(cadeia[i] != '\0')
{
// Coloca na pilha caso { [ ou (
if( cadeia[i] == '(' ||
cadeia[i] == '[' ||
cadeia[i] == '{')
push(p, cadeia[i]);
// Caso }]) ele compara pra ver se o topo é igual ao charactere
if( cadeia[i] == ')' ||
cadeia[i] == ']' ||
cadeia[i] == '}')
{
//Se a pilha for nula e achar um }, não é balanceada
if(p->topo == NULL)
return(0);
//Caso a pilha tiver elementos.
else
if(topo->simbolo == cadeia[i])
pop(p);
}
//Incrementa cadeia[i]
i++;
}
//Se tiver elementos no stack
if(p->tam = -1 )
return(1);
if (p->tam > -1)
return(0);
}
Here my try to implement my idea, only that the compiler accuses type error in the functions push and pop.
Push:
void push(Pilha p, char E)
{
No* novo = (No*)malloc(sizeof(No));
novo->simbolo = E;
novo->prox = p->topo;
p->topo = novo;
p->tam += 1;
}
Pop:
void pop(Pilha p)
{
No* aux = p->topo;
p->topo = p->topo->prox;
free(aux);
p->tam -= 1;
}
And my structs:
typedef struct No
{
char simbolo;
int top;
struct No* prox;
} No;
typedef struct pilha
{
No* topo;
int tam;
}Pilha;
From what I understand my mistakes are related to pointer manipulation, if you can point which are, I would be very grateful.
Thank you!