# Need help please – implementing a stack!

• 02-24-2009, 04:19 PM
sfe23
Need help please – implementing a stack!
I wonder why there is not even a single reply to my thread?!!:confused:

I need to implement a stack that converts infix arithmetic exp. to prefix.
I already implemented a stack class that has push, pop, peek and such methods. I made another class InToPre, below are my constructors:

I already have the algorithm (but I'm still stuck!):

If (operator stack is empty || operator > top of stack )
Push operator on stack

If ( operator < = top of stack || ‘( ‘ )
Repeat
Concatenate operand
Push operand to operand stack
While ( operator > top stack // stack is empty )
Push operator to operator stack
Case ‘ ) ‘ :
Repeat
Concatenate operand
Push operand to operand stack
Until ‘ (‘

default:
While (operator stack is not empty)
Concatenate operand
Push operand to operand stack
Pop operand stack and write to output

Algorithm Concatenate operand:
( the operator given )
Pop right operand
Pop left operand
Operand = operator + left operand + right operand
The problem is that I don't know how to check the priority of operands and in the concatenate operand, how to realize which one is left and which one is right?
Please give me some pointers to get going with this. your help is much appreciated :)
Below is what I have in my class InToPre:

public InToPre(String in) // default constructor
{
input = in;
int stackSize = input.length();
operatorStack = new StackInToPre(stackSize);
operandStack = new StackInToPre(stackSize);
}
//--------------------------------------------------------------
public String InToPre() // another constructor
{
for(int j=0; j<input.length(); j++) // for each char
{
char ch = input.charAt(j); // get it

if (Character.isDigit(ch)){
operandStack.push(ch); // push it to the operator stack
}

if (ch == '('){
operatorStack.push(ch)
}

if (isOperand(ch)){ // I already wrote the method isOperand

if ( !operandStack.isEmpty() || ch )
} // ?????