CHECK BRACKETS OF EXPRESSION ARE BALANCED or NOT using STACK.
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
using namespace std;
template <class Type>
class Brackets
{
private:
Type *Stack, *String;
bool Valid;
int Size, Top;
public:
Brackets(int Siz)
{
Size = Siz;
Stack = new Type[Size];
strcpy(Stack, "\0");
Valid = true;
Top = -1;
}
void Push(Type Ch)
{
if (Top == Size - 1)
{
cout << "\nString Overflowed......." << endl;
exit(1);
}
else
Stack[++Top] = Ch;
}
Type Pop()
{
if (IsEmpty())
{
cout << "\nStack Underflowed........" << endl;
exit(1);
}
else
return Stack[Top--];
}
void chkBrkt(Type Chr)
{
char Ch1, Ch2;
Ch1 = Chr;
if (Ch1 == '(' || Ch1 == '{' || Ch1 == '[')
Push(Ch1);
if (Ch1 == ')' || Ch1 == '}' || Ch1 == ']')
{
if (IsEmpty())
Valid = false;
else
{
Ch2 = Pop();
if (!((Ch2 == '(' && Ch1 == ')') || (Ch2 == '{' && Ch1 == '}') || (Ch2 == '[' && Ch1 == ']')))
Valid = false;
}
}
}
void Check()
{
if (!IsEmpty())
Valid = false;
if (Valid == true)
cout << "\nExpression's Brackets are Balanced and Expression Is Valid......\n" << endl;
else
cout << "\nExpression's Brackets are Unbalanced and Expression Is Invalid......\n" << endl;
}
inline bool IsEmpty()
{
return (Top == -1);
}
~Brackets()
{
cout << "\n\n\n\n******************PROGRAM ENDED******************\n\n\n\n" << endl;
}
};
int main()
{
Brackets<char> Obj(100);
char *Ch = new char[100];
cout << "Enter Expression: ";
cin >> Ch;
for (int I = 0; Ch[I] != '\0'; I++)
{
Obj.chkBrkt(Ch[I]);
}
Obj.Check();
getch();
return 0;
}
0 comments:
Post a Comment