parenthesis matching using stack

 //parenthsis matching problem

#include<iostream>

#include<string>

#define MS 100

using namespace std;

typedef struct{

int arr[MS];

int top;

}stack;

void init(stack *pts)

{

pts->top=-1;

}

int isfull(stack *pts)

{

if(pts->top==MS-1)

return 1;

else

return 0;

}

int isempty(stack *pts)

{

if(pts->top==-1)

return 1;

else

return 0;

}

void push(stack *pts,int data)

{

if(isfull(pts))

{

return;

}

else

{

++pts->top;

pts->arr[pts->top]=data;

}

}

int pop(stack *pts)

{

int temp;

if(isempty(pts))

{

return 9999;

}

else

{

temp=pts->arr[pts->top];

--pts->top;

return temp;

}

}

int peek(stack *pts)

{

if(isempty(pts)!=1)

{

return pts->arr[pts->top];

}

}

bool ismatch(char ch1,char ch2)

{

if(ch1=='('&&ch2==')')

return 1;

else if(ch1=='{'&&ch2=='}')

return 1;

else if(ch1=='['&&ch2==']')

return 1;

else return 0;

}

bool checkbalance(string exp)

{

stack s;

init(&s);

int i;

for(i=0;i<exp.length();i++)

{

//if input is an operand or operator then ignore it

if(exp[i]>='0'&&exp[i]<='9')

{

continue;

}

else if(exp[i]=='/'||exp[i]=='*'||exp[i]=='-'||exp[i]=='+'||exp[i]=='%')

{

continue;

}

else

{

//if input is an openning bracket then push it into stack

if(exp[i]=='('||exp[i]=='{'||exp[i]=='[')

{

push(&s,exp[i]);

}

/*if input is closing bracket then pop from stack and while popping 

check if the stack is empty or not , if empty then unbalanced*/

else if(exp[i]==')'||exp[i]=='}'||exp[i]==']')

{

if(isempty(&s)==1)

return 0;

else if((ismatch((char)peek(&s),exp[i]))!=1)

return 0;

else

pop(&s);

}

else

{

return 1;

}

}

}

//at the end of the expression check the stack is empty or not. if not empty then unbalanced 

if(isempty(&s)!=1)

return 0;

else

return 1;

}

int main()

{

string ip;

cout<<"Enter an expression:\n";

getline(cin,ip);

(checkbalance(ip))?cout<<"Expression is balanced":cout<<"Expression is unbalanced";

}







Comments

Popular Posts