STACK STACK BASIC STACK OPERATIONS BASIC STACK OPERATIONS PUSH ALGORITHM PUSH ALGORITHM POP ALGORITHM POP ALGORITHM EVALUATING A POSTFIX EXPRESSION EVALUATING A POSTFIX EXPRESSION
Stores a set of elements in a particular order Stack principle: LAST IN FIRST OUT = LIFO It means: the last element inserted is the first one to be removed Which is the first element to pick up? BACK
Basic Stack Operations The stack concept is introduced and two basic stack operations are discussed: Push Pop
BACK
STEP 1: [overflow ?] If Top = N then write “overflow” return [end of if statement] STEP 2: [increment Top] Top:=Top + 1 STEP 3: [insert new element] S[Top]:=X STEP 4: [finished] return S=name of stack X=element to be inserted Top=top pointer N=maximum size of stack BACK
STEP 1: [underflow ?] If Top = 0 then write “underflow” return [end of if statement] STEP 2: [delete elements] X:=S[Top] STEP 3: [decrement pointer] Top:=Top-1 STEP 4: [finished] return S=name of stack Top= top pointer X=variable used to store deleted elements BACK
STACK APPLICATION EVALUATING A POSTFIX EXPRESSION
Whenever an operand is encountered, push onto stack. Whenever operator is encountered, pop required number of arguments from operand stack and evaluate. Push result back onto stack.
1. Empty the operand stack 2. while there are more tokens 3. Get the next token 4. if the first character of the token is a digit 5. Push the integer onto the stack 6. else if the token is an operator 7. Pop the right operand off the stack 8. Pop the left operand off the stack 9. Evaluate the operation 10. Push the result onto the stack 11. Pop the stack and return the result
Another Example Expression: / * Execute Execute Execute 8 / Execute Execute Execute 8 * BACK