Vous êtes sur la page 1sur 10

This is one of the exercises that we programmed from the book (C++ How to Program ,Fifth

Edition By H. M. Deitel - Deitel & Associates, Inc., P. J. Deitel - Deitel & Associates, Inc.) but I
wrote it in Java Language. -mijaka_paz08@yahoo.com

21.12 Stacks are used by compilers to help in the process of evaluating expressions
and generating machine language code. In this and the next exercise, we
investigate how compilers evaluate arithmetic expressions consisting only of
constants, operators and parentheses.

Humans generally write expressions like 3 + 4 and 7 / 9 in which the operator (+


or / here) is written between its operands this is called infix notation.
Computers "prefer" postfix notation in which the operator is written to the
right of its two operands. The preceding infix expressions would appear in
postfix notation as 3 4 + and 7 9 /, respectively.

To evaluate a complex infix expression, a compiler would first convert the


expression to postfix notation and evaluate the postfix version of the
expression. Each of these algorithms requires only a single left-to-right pass of
the expression. Each algorithm uses a stack object in support of its operation,
and in each algorithm the stack is used for a different purpose.

In this exercise, you will write a C++ version of the infix-to-postfix conversion
algorithm. In the next exercise, you will write a C++ version of the postfix
expression evaluation algorithm. Later in the chapter, you will discover that
code you write in this exercise can help you implement a complete working
compiler.

Write a program that converts an ordinary infix arithmetic expression (assume


a valid expression is entered) with single-digit integers such as

(6 + 2) * 5 - 8 / 4

to a postfix expression. The postfix version of the preceding infix expression is

62+5*84/-
21.13 Write a program that evaluates a postfix expression (assume it is valid) such as

62+5*84/-

The program should read a postfix expression consisting of digits and operators
into a character array. Using modified versions of the stack functions
implemented earlier in this chapter, the program should scan the expression
and evaluate it.
Result:
38

Codes

/**
* @(#)StackTest.java
*no comments … I provided the code and you do your part to understand it.. =>
*
* @author ME
* @version 1.00 2010/8/3
*/
import java.io.*;
import java.util.*;

public class StackTest {

public static void main(String[] args) {

String input=" ";


BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) );

System.out.println("Enter infix expression operators(+-*/%) and digits(0-9): ");


try{
input=dataIn.readLine();
}catch(IOException w){ System.out.println("Error"+w);}

input=input+")";
Stack stack=new Stack(input.length());
stack.push('(');

String post=stack.convert(input);
StringTokenizer output=new StringTokenizer(post);
System.out.println("\npostfix expression:");

while(output.hasMoreTokens())
{
System.out.print(output.nextToken()+" ");
}

Evaluator_Postfix evaluate=new Evaluator_Postfix(post.length());

int answer=evaluate.produce(post);
System.out.println("\nresult: ");
System.out.println(answer);
System.exit(0);

/**
* @(#)Stack.java
*This is a stack in int array
*
* @author ME
* @version 1.00 2010/8/3
*/
import java.io.*;
import java.util.*;

public class Stack{

private int size;


private int top;
private char[] values;

public Stack(int size){


this.size = size;
values = new char[size];
top = -1;
}

public void push(char data)


{ if(!isFull()){

top++;
values[top] = data;
}
}

public boolean isFull(){


if(top < size-1){
return false;
}
else{
return true;
}
}

public boolean isEmpty(){


if(top == -1){
return true;
}
else{
return false;
}
}
public char pop()
{
char retVal = ' ';
if(!isEmpty())
{
retVal=values[top];
top--;
}

return retVal;
}

public char stackTop()


{ int temp=top;
char retVal = ' ';

if(!isEmpty()) {
retVal=values[temp];
temp--;
}
return retVal;

public int precedence(char it)


{
if(it=='*'||it=='^')
return 6;

else if(it=='/')
return 5;

else if(it=='%')
return 4;

else if(it=='+')
return 3;

else if(it=='-')
return 2;

else
return 1;
}

public String convert(String in_put)


{
StringBuffer postfix=new StringBuffer(in_put.length());

int i=0;
char c;
String word=" ";

while(i<in_put.length())
{
c=in_put.charAt(i);
if(Character.isDigit(c))
postfix.append(c).append(" ");

if(c=='(')
push('(');

if(c=='*'||c=='/'||c=='%'||c=='+'||c=='-')
{
char v=stackTop();
if(v=='*'||v=='/'||v=='%'||v=='+'||v=='-')
{
if(precedence(v)>=precedence(c))
{
{
postfix.append(pop()).append(" ").toString();
}

}
}
push(c);
}

if(c==')')
{ char st=stackTop();
while(st!='('&&!isEmpty())
{

postfix.append(pop()).append(" ").toString();
st=stackTop();

}
pop();
}

i++;

}
return postfix.toString();

}//end of inner while(token)


public void print()
{
char temp=values[top];
System.out.println("Stack content");
while(!isEmpty())
{
System.out.println("\n"+temp);
temp=values[top--];
}

/**
* @(#)evaluator.java
*This is a stack in char array
*
* @author ME
* @version 1.00 2010/8/4
*/

import java.io.*;
import java.util.*;

public class Evaluator_Postfix {

private int size;


private int top;
private int[] values;
private int valEx;

public Evaluator_Postfix(int size){


this.size = size;
values = new int[size];
top = -1;
}
public void push(int data)
{ if(!isFull()){

top++;
values[top] = data;
}
}

public boolean isFull(){


if(top < size-1){
return false;
}
else{
return true;
}
}

public boolean isEmpty(){


if(top == -1){
return true;
}
else{
return false;
}
}
public int pop()
{
int retVal = 0;
if(!isEmpty())
{
retVal=values[top];
top--;
}

return retVal;
}

public int produce(String post_fix) {

post_fix=post_fix+"\0";
int i=0;
int ans;
int x,y;
while(i<post_fix.length())
{
char c=post_fix.charAt(i);

if(Character.isDigit(c))
{
int l=(c-'0');
push(l);

if(c=='*'||c=='/'||c=='%'||c=='+'||c=='-')
{
x=pop();
y=pop();

//calculating

if(c=='*'){
ans=x*y;
push(ans);
}
if (c=='/'){
if(x<y)
{
ans=y/x;
push(ans);
}

else{
ans=x/y;
push(ans);
}
}
if (c=='%'){
ans=x%y;
push(ans);
}
if(c=='+'){
ans=x+y;
push(ans);
}
if(c=='-'){
if(x<y)
{
ans=y-x;
push(ans);
}

else{
ans=x-y;
push(ans);
}
}

if(c=='\0')
{
while(!isEmpty()){
valEx=pop();
}
}
i++;
}

return valEx;
}

For thanking me you can go to my facebook account. And just say


Thank You.!!

Vous aimerez peut-être aussi