Problem Statement: In many language program mostly syntax error occurs due to unbalancing delimiter such as (),{},[]. Write C++ program using stack to check whether given expression is well parenthesized or not.
Note: Scroll Horizontally to see the full line of code.
#include <iostream>
#include <string>
using namespace std;
string s;
class Stack
{
char *arr;
int top = -1;
public:
Stack()
{
arr = new char[100];
top = -1;
}
void push(char x)
{
top++;
arr[top] = x;
}
void pop()
{
if (top == -1)
{
cout << "NO element in stack" << endl;
return;
}
top--;
}
char Top()
{
return arr[top];
}
bool empty()
{
return top == -1;
}
};
Stack st;
bool isValid(string s)
{
int n = s.length();
bool ans = true;
for (int i = 0; i < n; i++)
{
if (s[i] == '(' or s[i] == '[' or s[i] == '{')
{
st.push(s[i]);
}
else if (s[i] == ')')
{
if (!st.empty() and st.Top() == '(')
{
st.pop();
}
else
{
ans = false;
break;
}
}
else if (s[i] == ']')
{
if (!st.empty() and st.Top() == '[')
{
st.pop();
}
else
{
ans = false;
break;
}
}
else if (s[i] == '}')
{
if (!st.empty() and st.Top() == '{')
{
st.pop();
}
else
{
ans = false;
break;
}
}
}
if (!st.empty())
{
return false;
}
return ans;
}
int main()
{
char cont = 'y';
while (cont == 'y')
{
cout << "Enter the parenthesise expression: ";
cin >> s;
if (isValid(s))
{
cout << "Expression is well parenthesized!!!" << endl;
}
else
{
cout << "Expression is not well parenthesized!!!" << endl;
}
cout << "Do you want to continue? (y/n): ";
cin >> cont;
}
cout << "Program Ended Successfully!!!!" << endl;
return 0;
}
Comments
Post a Comment