Tuesday, April 30, 2019

Hackerrank Balanced Brackets Using Stack (Linked List Implementation)

#include <iostream>
/* #include <stack> */
using namespace std;

typedef char intt;

struct stkNode
{
    intt val;
    struct stkNode *nxtNode;
};

struct stkNode *stkHEAD = NULL;

void stkPush(intt newVal);
void stkPop();

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    string s;
    int n;
    cin >> n;

    while (n--)
    {
        stkHEAD = NULL;
        bool fl = 0;
        cin >> s;

        for (int i = 0; i < s.size(); i++)
        {
            if (s[i] == '(' or s[i] == '[' or s[i] == '{')
            {
                stkPush(s[i]);
            }
            else
            {
                if (stkHEAD != NULL)
                {
                    char ch = stkHEAD->val;
                    if ((s[i] == ')' && ch == '(') ||
                            (s[i] == '}' && ch == '{') ||
                            (s[i] == ']' && ch == '['))
                    {
                        stkPop();
                    }
                    else
                    {
                        fl = 1;
                        break;
                    }
                }
                else
                {
                    fl = 1;
                    break;
                }
            }
        }

        if (stkHEAD != NULL)
            fl = 1;

        if (fl == 1)
            cout << "NO\n";
        else
            cout << "YES\n";
    }

    return 0;
}

void stkPush(intt newVal)
{
    struct stkNode *tmp = new stkNode;
    tmp->val = newVal;
    tmp->nxtNode = stkHEAD;

    stkHEAD = tmp;
}

void stkPop()
{
    if (stkHEAD == NULL)
    {
//        cout << "Stack Empty\n";
        return;
    }
    else
    {
        intt ret = stkHEAD->val;
        stkHEAD = stkHEAD->nxtNode;
        return;
    }
}