Sunday 5 February 2017

Symbol Balancing using Stacks : Java program and C program

Algorithm
Step 1: Start
Step 2: Read the expression
Step 3: Scan every character of expression
          If scanned character is
          3.1: any open symbol like ( , {, [ then   push it onto the stack
          3.2: any closed symbol then
                    3.2.1 if stack is empty then invalid expression
                    3.2.2 else  pop the top most element of stack
                              if the symbol popped is not the corresponding opening
symbol, then invalid expression
Step 4: If stack is not empty then invalid expression

Step 5: Stop

Java program
package p1;

import java.util.Scanner;
class SNode
{
char data;
SNode next;
}
class Stack
{
SNode top=null;
public void push(char val)
{
SNode newnode=new SNode() ;
newnode.data=val;
newnode.next=null;
if(top==null)
top=newnode;
else
{
newnode.next=top;
top=newnode;
}
}
public char pop()
{
char temp=top.data;
top=top.next;
return temp;
}
}
public class SymbolBalancingDemo 
{
public static void main(String[] args)
{
Stack ob=  new Stack();
Scanner sc = new Scanner(System.in);
System.out.println("enter infix expression");
String infix=sc.next();
int flag=0;
for(int i=0;i<infix.length();i++)
{
char ch=infix.charAt(i);
if(ch == '(' || ch== '{' || ch =='[')
ob.push(ch);
else if (ch == ')' || ch== '}' || ch ==']')
{
if(ob.top == null)
flag=1;
else 
{
char temp=ob.pop();
if(ch ==')' && (temp == '{' || temp == '['))
flag=1;
else if(ch ==']' && (temp == '{' || temp == '('))
flag=1;
else if(ch =='}' && (temp == '(' || temp == '['))
flag=1;

}
}
if(flag ==1)
break;
}
if(ob.top != null)
flag=1;
if(flag == 1)
System.out.println("invalid expression");
else
System.out.println("valid expression");
}

}

========C program=================
#include<stdio.h>
#include <process.h>
#include <string.h>
#define MAX 50
char stack[MAX];
int top=-1;
void push(char);
char pop();
void main()
{
 char exp[MAX],temp;
 int i, flag=1;
printf("Enter an expression : ");
gets(exp);
for(i=0;i<strlen(exp);i++)
{
if(exp[i]=='(' || exp[i]=='{' || exp[i]=='[')
       push(exp[i]);
if(exp[i]==')' || exp[i]=='}' || exp[i]==']')
if(top == -1)
{
       flag=0; break;
}
else
{
temp=pop();
if(exp[i]==')' && (temp=='{' || temp=='['))
flag=0;
if(exp[i]=='}' && (temp=='(' || temp=='['))
flag=0;
if(exp[i]==']' && (temp=='(' || temp=='{'))
flag=0;
}
}
if(top>=0)
         flag=0;
if(flag==1)
printf("\n Valid expression");
else
printf("\n Invalid expression");
}
void push(char item)
{
 if(top == MAX-1)
 {
  printf("stack is full");
  return;
 }
 top=top+1;
 stack[top]=item;
}

char pop()
{
 if(top == -1)
 {
  printf("stack empty");
  return;
 }
 char temp;
 temp=stack[top];
 top=top-1;
 return temp;
}

No comments:

Post a Comment