#### All Algorithms Related To Stack

by

, 02-08-2011 at 07:47 AM (18125 Views)
Stack is a collation of an arrayarrof sizeMAXSIZEand an integer top. Top is initialized by−1;

1)## Algorithm for checking whether the stack is full or not.

isfull (stack *s)

{

If s−>top is equals to MAXSIZE −1 return true;

Else return false;

}

2)## Algorithm for inserting an element into the stack.

Push (stack *s, item)

{

If (! isfull(s))

{

Increment s−>top by 1;

Assign item into s−>arr [s−>top];

}

}

3)## Algorithm for checking whether the stack is empty or not.

isempty (stack *s)

{

If s−>top is equals to −1 return true;

Else return false;

}

4)## Algorithm for deleting an element from the stack.

Item Pop (stack *s)

{

If (!isempty(s))

{

Assign s−>arr [s−>top] into item;

Decrement s−>top by 1;

Return item;

}

}

5)## Algorithm for viewing the topmost element of the stack.

Item Peek (stack *s)

{

If (! isempty(s))

{

Assign s−>arr [s−>top] into item;

Return item;

}

}

6)## Algorithm for evaluating a postfix expression.

Evaluate (input string)

{

Initialize stack;

While (input string is not empty)

{

Scan each digit from the input string and assign it into symbol.

If (symbol is an operand) push symbol into the stack.

Else

{

Pop two elements from the stack and perform the appropriate operation and push the result into the stack.

}

}

Pop the element from the stack and return it.

}

7)## Algorithm for converting an infix expression to postfix expression.

Convert (input string)

{

Initialize stack;

While (input string is not empty)

{

Scan each digit from the input string and assign it into symbol.

If (symbol is an operand) place it into the output string.

Else

{

If (symbol is equals to ‘(‘) push symbol into the stack.

Else if (symbol is equals to ‘)’) pop the elements from the stack and assign it into the output string until ‘(‘.

Else

{

While (precedence of symbol is les than or equals to the precedence of peek (stack))

Pop the elements and place those elements into the output string.

Push symbol into the stack.

}

}

}

Pop the elements from the stack and place those elements into the output string until stack is not empty.

Print output string.

}