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.
#include<iostream>
using namespace std;
#define size 20
class stack{
char stk[size];
int top;
public:
stack(){
top=-1;
}
void push(char x){
stk[++top]=x;
}
char pop(){
char temp=stk[top];
top--;
return temp;
}
bool empty(){
if(top==-1)
return true;
else return false;
}
char tops(){
char ch;
ch=stk[top];
return ch;
}
};
int main(){
stack st;
string s;
char ch, temp;
int i=0;
cout<<"\nEnter the expression : ";
cin>>s;
if(s[0]==')' || s[0]==']' || s[0]=='}')
cout<<"\nInvalid";
else{
while(s[i]!='\0'){
ch=s[i];
switch(ch){
case '(' : st.push(ch);break;
case '{' : st.push(ch);break;
case '[' : st.push(ch);break;
case ')' : if(st.tops()=='(')temp=st.pop();break;
case '}' : if(st.tops()=='{')temp=st.pop();break;
case ']' : if(st.tops()=='[')temp=st.pop();break;
}
i++;
}
if(st.empty())
cout<<"\nValid ";
else
cout<<"\nInvalid";
}
return 0;
}
#include<iostream>
using namespace std;
#define size 20
class stack{
char stk[size];
int top;
public:
stack(){
top=-1;
}
void push(char x){
stk[++top]=x;
}
char pop(){
char temp=stk[top];
top--;
return temp;
}
bool empty(){
if(top==-1)
return true;
else return false;
}
char tops(){
char ch;
ch=stk[top];
return ch;
}
};
int main(){
stack st;
string s;
char ch, temp;
int i=0;
cout<<"\nEnter the expression : ";
cin>>s;
if(s[0]==')' || s[0]==']' || s[0]=='}')
cout<<"\nInvalid";
else{
while(s[i]!='\0'){
ch=s[i];
switch(ch){
case '(' : st.push(ch);break;
case '{' : st.push(ch);break;
case '[' : st.push(ch);break;
case ')' : if(st.tops()=='(')temp=st.pop();break;
case '}' : if(st.tops()=='{')temp=st.pop();break;
case ']' : if(st.tops()=='[')temp=st.pop();break;
}
i++;
}
if(st.empty())
cout<<"\nValid ";
else
cout<<"\nInvalid";
}
return 0;
}
No comments:
Post a Comment