Sunday 5 February 2017

Evaluating Postfix Expression Using Stack : Java Program and C Program

Algorithm
Step 1: Start
Step 2: Read the postfix expression
Step 3: Scan every character of postfix expression
          3.1 If scanned character is operand then push it onto the stack
          3.2 If scanned character is operator, then
                    a. pop the top two elements from the stack as A and B
                    b. Perform the operation on B and A
                    c. Push the result back into stack
Step 4: Print the top most element of the stack

Step 5: Stop

import java.util.Scanner;
class SNodei
{
int data;
SNodei next;
}
class Stacki
{
SNodei top=null;
public void push(int val)
{
SNodei newnode=new SNodei() ;
newnode.data=val;
newnode.next=null;
if(top==null)
top=newnode;
else
{
newnode.next=top;
top=newnode;
}
}
public int pop()
{
int temp=top.data;
top=top.next;
return temp;
}
}

public class PostfixEvaluation
{
public static void main(String[] args)
{
Stacki ob = new Stacki();
Scanner sc = new Scanner(System.in);
System.out.println("enter postfix expression");
String postfix;
postfix=sc.next();
for(int i=0;i<postfix.length();i++)
{
char ch=postfix.charAt(i);
if(ch == '*' ||ch == '/' ||ch == '+' ||ch == '-'|| ch == '%' )
{
int v1,v2,v3=0;
v1=ob.pop();
v2=ob.pop();
switch(ch)
{
   case '+': v3=v2+v1;
      break;
   case '-': v3=v2-v1;
      break;
   case '*': v3=v2*v1;
      break;
   case '/': v3=v2/v1;
      break; 
}
ob.push(v3);
}
else if(ch>='a' && ch<='z')
{
  int val;
  System.out.println("enter the value of "+ch);
  val=sc.nextInt();
  ob.push(val);
}
}
System.out.println("Result ="+ob.pop());
}
}

============================================================

#include<stdio.h>
#include <process.h>
#include <string.h>
#define MAX 50
char stack[MAX];
int top=-1;
void push(float);
float pop();
void main()
{
char exp[MAX],temp,ch;
int i;
float op1,op2,value;
printf("Enter an expression : ");
gets(exp);
for(i=0;i<strlen(exp);i++)
{
ch=exp[i];
if(isdigit(ch))
push((float)ch-'0');
else
{
op2=pop();
op1=pop();
switch(ch)
{
case '+':
value=op1+op2;
break;
case '-':
value=op1-op2;
break;
case '*':
value=op1*op2;
break;
case '/':
value=op1/op2;
break;
case '%':
value=(int)op1%(int)op2;
break;
}
push(value);
}
}
printf("\n Result=%f",pop());
}

void push(float item)
{
if(top == MAX-1)
{
printf("stack is full");
return;
}
top=top+1;
stack[top]=item;
}

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

No comments:

Post a Comment