main.cpp
=================================================
#include<iostream>
using namespace std;
#include"Stack.h"
bool ArePair(char open, char close)
{
if (open == '(' && close == ')')
return true;
else if (open == '{' && close == '}')
return true;
else if (open == '[' && close == ']')
return true;
return false;
}
bool IsBalanced(char*Exp,int n)
{
Stack s;
for (int i = 0; i < n; i++)
{
if (Exp[i] == '(' || Exp[i] == '[' || Exp[i] == '{')
s.Push(Exp[i]);
else if (Exp[i] == ')' || Exp[i] == ']' || Exp[i] == '}')
{
if (s.IsEmpty() || !ArePair(s.Top(), Exp[i]))
return false;
else
s.Pop();
}
}
return s.IsEmpty() ? true:false;
}
int main()
{
char Exp[100];
cout << "Enter characters: ";
cin >> Exp;
if (IsBalanced(Exp, strlen(Exp)))
cout << "Balanced!" << endl;
else
cout << "Not Balanced!" << endl;
return 0;
}
=================================================
=================================================
Stack.h
=====================================
#pragma once
using namespace std;
class Stack
{
private:
char A[100];
int top;
public:
Stack()
{
top = -1;
}
void Push(int x)
{
if (top == A[99])
cout << "Stack OverFlow!" << endl;
A[++top] = x;
}
void Pop()
{
if (top == -1)
cout << "Stack is Empty!" << endl;
top--;
}
char Top()
{
return A[top];
}
void print()
{
cout << "Stack: ";
for (int i = 0; i <= top; i++)
{
cout << A[i] << " ";
}
cout << "\n";
}
bool IsEmpty()
{
if (top == -1)
return true;
return false;
}
};
=====================================
No comments:
Post a Comment