Write a programe that will check for brackets in a mathematical expression whether it is balanced or not.
Sample Inputs : Sample Outputs:
{({})([])}} Closing bracket overflow
[{{({})([])}}] Balanced
[{{({})([])})] Unmatched
(()){{{[]}{[][]}} Opening bracket overflow
#include <stdio.h>
#include <stdlib.h>
#define bool int
struct Node {
char d;
struct Node* next;
};
void push(struct Node** top_r, int new_d);
int pop(struct Node** top_r);
bool ismatching(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 isBalanced(char exp[])
{
int i = 0;
struct Node* stack = NULL;
while (exp[i])
{
if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
push(&stack, exp[i]);
if (exp[i] == '}' || exp[i] == ')'
|| exp[i] == ']') {
if (stack == NULL)
return 0;
else if (!ismatching(pop(&stack), exp[i]))
return 0;
}
i++;
}
if (stack == NULL)
return 1;
else
return 0;
}
int main()
{
char exp[100] = "{()}[]";
if (isBalanced(exp))
printf("Balanced \n");
else
printf("Not Balanced \n");
return 0;
}
void push(struct Node** top_r, int new_d)
{
struct Node* new_node
= (struct Node*)malloc(sizeof(struct Node));
if (new_node == NULL) {
printf("Overflow \n");
getchar();
exit(0);
}
new_node->d = new_d;
new_node->next = (*top_r);
(*top_r) = new_node;
}
int pop(struct Node** top_r)
{
char res;
struct Node* top;
if (*top_r == NULL) {
printf("Overflow \n");
getchar();
exit(0);
}
else {
top = *top_r;
res = top->d;
*top_r = top->next;
free(top);
return res;
}
}
Comments
Leave a comment