About

Kannur University btech CSE study materials, question papers, syllabus . . .

Thursday, July 4, 2013

S4- dsa lab - VALIDITY OF EXPRESSION

         /*              VALIDITY OF EXPRESSION       */

import java.io.*;
class Stack
{
int top=0;
char a[]=new char[100];
void push(char d)
{
top++;
a[top]=d;
}
char pop()
{
char d=a[top];
top--;
return d;
}
int em()
{ if(top==0)
return 1;
else return 0;
}}
class Expression
{
public static void main(String args[])throws Exception
{
DataInputStream nn=new DataInputStream(System.in);
System.out.print("enter the Expression: ");
String s=nn.readLine();
Stack ss=new Stack();
int n=s.length();
int flag=0,cc=0;
char d;
for(int i=0;i<n&&cc>=0;i++)
{
char c=s.charAt(i);
switch(c)
{
case '(' : ss.push('(');cc++;break;
case '{' : ss.push('{');cc++;break;
case '[' : ss.push('[');cc++;break;
case ')' : if((d=ss.pop())!='(')
               flag=1;cc--;break;
case '}' : if((d=ss.pop())!='{')
               flag=1;cc--;break;
case ']' : if((d=ss.pop())!='[')
               flag=1;cc--;break;
}
}
if((flag==0)&&(ss.em()==1))
{System.out.println("valid Expression ");
}
else
{System.out.println("invalid Expression ");
}}}

OUTPUT

enter the Expression: {a+(b*c)-d)
invalid Expression

enter the string  : {a+(b*c)-d}

valid Expression

0 comments:

Post a Comment