Follow This Blog For more... 😊

Check for Balanced Brackets in an expression (well- formedness) using Stack.| using C language | Data Structure |

👨‍💻Check for Balanced Brackets in an expression (well-formedness) using Stack.
Solution:

LOGIC :

Each time, when an open parenthesis is encountered push it into the stack, and when a closing parenthesis is encountered, match it with the top of the stack and pop it. If the stack is empty at the end, return Balanced otherwise, Unbalanced.

CODE :


    
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #define N 500
    char stack[N];
    int top=-1;
    void push_in_stack(char a);
    void pop_from_stack();

    main()
    {
        int i;
        char exp[N];
        printf("Enter the Expression:");
        gets(exp);
        for(i=0;exp[i]!=NULL;i++)
        {
            if(exp[i]=='('||exp[i]=='{'||exp[i]=='[')
            {
                push_in_stack(exp[i]);
            }
            else if((exp[i]==')' && stack[top]=='(')||(exp[i]=='}' && stack[top]=='{')||(exp[i]==']' && stack[top]=='['))
            {
                pop_from_stack();
            }
            else if(exp[i]==')'||exp[i]=='}'||exp[i]==']')
            {
                printf("\nExpression is Unbalenced !!!\n");
                exit(0);
            }
        }
            if(top==-1)
            {
                printf("\nExpression is balenced !!!\n");
            }
            else
            {
                printf("\nExpression is Unbalenced !!!\n");
            }
    }

    void push_in_stack(char a)
    {
        if(top>=N)
        {
            printf("Stack is overflow !!!!");
        }
        else
        {
            top++;
            stack[top]=a;
        }
    }

    void pop_from_stack()
    {
        stack[top]='\0';
        top--;
    }

OUTPUT:





Comments

Popular Posts