Data Structure Lab :
Practical D26:
In any 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.
// Author : SE CSE GURU
#include<iostream>
#include<string>
using namespace std;
class Parenthesis{
public:
int Top,max;
char Stack[30];
Parenthesis(){
Top=-1;
max=29;
}
void push(char);
char pull();
int isFull();
int isEmpty();
};
void Parenthesis::push(char ch){
if(isFull()){
cout<<"Stack is Overflow "<<endl;
}
else{
Top++;
Stack[Top]=ch;
}
}
char Parenthesis::pull(){
if(isEmpty()){
cout<<"Stack is Underflow "<<endl;
}
else{
return(Stack[Top--]);
}
}
int Parenthesis::isFull(){
if(Top==max){
return 1;
}
else{
return 0;
}
}
int Parenthesis::isEmpty(){
if(Top==-1){
return 1;
}
else{
return 0;
}
}
int main(){
char ch,choice;
string str;
int length;
do
{
Parenthesis obj;
cout<<"Enter expression : "<<endl;
cin>>str;
length=str.size();
int flag=0;
for(int i=0;i<length;i++){
ch=str[i];
if (ch=='('||ch=='['||ch=='{'){
obj.push(ch);
}
else{
if(!( (ch==')' && obj.pull()=='(') || (ch==']' && obj.pull()=='[') || (ch=='}' && obj.pull()=='{') ) ){
flag=1;
break;
}
}
}
if(obj.isEmpty() && flag==0){
cout<<"The Expression is well parenthesized :) "<<endl;
}
else{
cout<<"The Expression is NOT well parenthesized :( "<<endl;
}
cout<<"Do you want to continue (y or n)"<<endl;
cin>>choice;
}while(choice=='y');
return 0;
}
Comments
Post a Comment