Answer to Question #234672 in C for Tommy

Question #234672

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


1
Expert's answer
2021-09-08T16:04:26-0400
#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;
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS