TOPICS TO BE DISCUSSED • STACK • STACK OPERATIONS • PUSH ALGORITHM • POP ALGORITHM • USES OF STACK • THE TOWER OF HANOI
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
PUSH ALGORITHM S=name of stack X=element to be inserted Top=top pointer N=maximum size of stack 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 BACK
POP ALGORITHM S=name of stack Top= top pointer X=variable used to store deleted elements 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 BACK
SOME USES OF STACK • Stacks are used for: • Any sort of nesting (such as parentheses) • Evaluating arithmetic expressions (and other sorts of expression) • Implementing function or method calls • Keeping track of previous choices (as in backtracking) • Keeping track of choices yet to be made (as in creating a maze) BACK
THE TOWER OF HANOI In the great temple of Brahma in Benares, on a brass plate under the dome that marks the center of the world, there are 64 disks of pure gold that the priests carry one at a time between these diamond needles. According to Brahma's immutable law: No disk may be placed on a smaller disk. In the beginning of the world all 64 disks formed the Tower of Brahma on one needle. Now, however, the process of transfer of the tower from one needle to another is in mid course. When the last disk is finally in place, once again forming the Tower of Brahma but on a different needle, then will come the end of the world and all will turn to dust.
The Tower of HanoiA Stack-based Application • GIVEN: three poles • a set of discs on the first pole, discs of different sizes, the smallest disc at the top • GOAL: move all the discs from the left pole to the right one. • CONDITIONS: only one disc may be moved at a time. • A disc can be placed either on an empty pole or on top of a larger disc.
TOWER OF HANOI INITIAL STATE
TOWER OF HANOI MOVE1
TOWER OF HANOI MOVE 2
TOWER OF HANOI MOVE 3
TOWER OF HANOI MOVE 4
TOWER OF HANOI MOVE 5
TOWER OF HANOI MOVE 6
TOWER OF HANOI BACK MOVE 7(FINAL STATE)