stack stack basic stack operations basic stack operations push algorithm push algorithm pop...
TRANSCRIPT
STACKS
STACK BASIC STACK OPERATIONS PUSH ALGORITHM POP ALGORITHM EVALUATING A POSTFIX EXPRESSION
STACK 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
PUSH ALGORITHM
STEP 1: [overflow ?] If Top = N then write “overflow” return [end of if statement]STEP 2: [increment Top] Top:=Top + 1STEP 3: [insert new element] S[Top]:=XSTEP 4: [finished] return
S=name of stackX=element to be insertedTop=top pointerN=maximum size of stack
BACK
POP ALGORITHM
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-1STEP 4: [finished] return
S=name of stackTop= top pointerX=variable used to store deleted elements
BACK
STACK APPLICATION
EVALUATING A POSTFIX EXPRESSION
LOGIC… 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.
Algorithm for evaluation1. Empty the operand stack2. while there are more tokens3. Get the next token4. if the first character of the token is a digit5. Push the integer onto the stack6. else if the token is an operator7. Pop the right operand off the stack8. Pop the left operand off the stack9. Evaluate the operation10. Push the result onto the stack11. Pop the stack and return the result
R P N (R e ve rs e P o lis h N o ta tio n) e xpre s s io n 2 3 +
3
2
o pe randStac k e m pty
3. Ide ntify + a s a n ope ra tor B e gin the proc e s s of e va lua ting + .
4 . ge tO pe ra nds () pops s ta c k tw ic e a nd a s s igns 3 to r ight a nd 2 to le f t.
5 . c om pute () e va lua te s le f t + r ight a nd re turns the va lue 5 . R e turn va lue is pus he d on the s ta c k .
5
1. Ide ntify 2 a s a n ope ra nd. P us h in te ge r 2 on the s ta c k .
C urre nt o pe randStac k
2
3
2
2. Ide ntify 3 a s a n ope ra nd. P us h in te ge r 3 on the s ta c k .
Sc an o f E xpre s s io n and Ac tio n
Another ExampleExpression: 5 3 - 6 + 8 2 / 1 2 + - *
5 2 8
3
5
Execute 5 - 3 Execute 2 + 6
8
8
2
8
8
Execute 8 / 2
4
8
1
4
8
2
1
4
8 Execute 1 + 2
3
4
8
Execute 4 - 3
1
8
Execute 8 * 1
8
3
5
3
5
6
2
BACK
THANKS
BACK