#include <stdio.h>
#include <stdlib.h>
#define bool int
struct Node {
char d;
struct Node* nxt;
};
void push(struct Node** top_ref, int new_data)
{
struct Node* new_node
= (struct Node*)malloc(sizeof(struct Node));
if (new_node == NULL) {
printf("Overflow");
getchar();
exit(0);
}
new_node->d = new_data;
new_node->nxt = (*top_ref);
(*top_ref) = new_node;
}
int pop(struct Node** top_ref)
{
char res;
struct Node* top;
if (*top_ref == NULL) {
printf("Overflow");
getchar();
exit(0);
}
else {
top = *top_ref;
res = top->d;
*top_ref = top->nxt;
free(top);
return res;
}
}
bool is_matching_pair(char c1, char c2)
{
if (c1 == '(' && c2 == ')')
return 1;
else if (c1 == '{' && c2 == '}')
return 1;
else if (c1 == '[' && c2 == ']')
return 1;
else
return 0;
}
bool are_balanced(char expression[])
{
int i = 0;
struct Node* stack = NULL;
while (expression[i])
{
if (expression[i] == '{' || expression[i] == '(' || expression[i] == '[')
push(&stack, expression[i]);
if (expression[i] == '}' || expression[i] == ')'
|| expression[i] == ']') {
if (stack == NULL)
return 0;
else if (!is_matching_pair(pop(&stack), expression[i]))
return 0;
}
i++;
}
if (stack == NULL)
return 1;
else
return 0;
}
int main()
{
char expression[100] = "(({()}[])";
if (are_balanced(expression))
printf("Balanced \n");
else
printf("Not Balanced \n");
return 0;
}
Comments
Leave a comment