STACK STACK STACK OPERATIONS STACK OPERATIONS PUSH ALGORITHM PUSH ALGORITHM POP ALGORITHM POP...

Post on 17-Jan-2016

256 views 1 download

Tags:

Transcript of STACK STACK STACK OPERATIONS STACK OPERATIONS PUSH ALGORITHM PUSH ALGORITHM POP ALGORITHM POP...

STACK

STACK STACK OPERATIONS PUSH ALGORITHM POP ALGORITHM USES OF STACK THE TOWER OF HANOI

TOPICS TO BE DISCUSSED

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 ALGORITHMSTEP 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 ALGORITHMSTEP 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

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

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 HANOI

◦ 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.

The Tower of HanoiA Stack-based Application

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

MOVE 7(FINAL STATE) BACK

THANKS..

BACK