Header Ads

Parenthesis Balanced Check with stack in C++

Problem : Parenthesis Balanced Check Use Stack in C++.

#include<iostream>

#include<stack>

using namespace std;


    bool checkBrackets()

    {

        string n;

        int flag=0;

        stack<char>Stack;

        cout<<"Enter a expression for check parenthesis balanced:"<<"";

        cin>>n;

        for(int i=0; i<n.length(); i++)

        {

            if(n[i]=='(' || n[i]=='{' || n[i]=='[')

            {

                Stack.push(n[i]);

                flag=1;

            }

            if(Stack.empty())

            {

                return false;

            }


            char m=Stack.top();


             if (!Stack.empty()) {

            if (n[i] == '}') {

                if (Stack.top() == '{')

                {

                    Stack.pop();

                    continue;

                }

                else

                    break;

            }

            if (n[i] == ']') {

                if (Stack.top() == '[') {

                    Stack.pop();

                    continue;

                }

                else

                    break;

            }

            if (n[i] == ')') {

                if (Stack.top() == '(') {

                    Stack.pop();

                    continue;

                }

                else

                    break;

            }

        }

        else {

            break;

        }

    }

    if ((Stack.empty()) && (flag == 1))

        cout << "This is parenthesis is balanced." << endl;

    else

    {

        cout << "This parenthesis is not balanced." << endl;

    }

}

int main()

{

     checkBrackets();

}

Console Output:



No comments

Powered by Blogger.