#include void easy(int N) { if (N < 1) return; easy(N-2); cout<
Stacks
2
Stacks
3
Stacks
4
Stacks
5
Problems that Use Stacks • The runtime stack used by a process (running program) to keep track of methods in progress • Search problems • Undo, redo, back, forward
Stacks
6
Simple class for Stacks class stack{ private: int stack1[100]; int data; public: void push(int*, int) int pop(int*); peep(int i); update(int update_elt, int i); }; Stacks
7
push //Global variables, size=100; top=-1; flag=0; void stack::push(int stack1[ ], int d) { if (top==size-1) flag=0; //checking overflow conditions else { flag=1; top++; stack1[top]=d; } } Stacks
8
pop int stack::pop() { int popped_elt; if (top==-1) {flag=0; return -1; } else { flag=1; popped_elt=stack1[top]; Stack1[top]=NULL; //optional top--; return popped_elt; } } Stacks
9
peep int stack::peep(int i) {int peeped_elt; if (top-i+1<0) {peeped_elt=-1; flag=0; } else{ flag=1; peeped_elt=stack1[top-i+1]; return peeped_elt; } }
Stacks
10
update int stack::update(int update_elt, int i) { if (top-i+1<0) { flag=0; return -1; } else { flag=1; stack1[top-i+1]=update_elt; } } Stacks
11
The Towers of Hanoi A Stack-based Application – GIVEN: three poles – a set of discs on the first pole, discs of different sizes, the smallest discs 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.
Stacks
12
Towers of Hanoi
Stacks
13
Towers of Hanoi
Step 1 Stacks
14
Towers of Hanoi
Step 2 Stacks
15
Towers of Hanoi
Step 3 Stacks
16
Towers of Hanoi
Step 4 Stacks
17
Towers of Hanoi
Step 5 Stacks
18
Towers of Hanoi
Step 6 Stacks
19
Towers of Hanoi
Step 7 Stacks
20
Towers of Hanoi – Recursive Solution void hanoi (int discs, Stack fromPole, Stack toPole, Stack aux) { Disc d; if( discs >= 1) { hanoi(discs-1, fromPole, aux, toPole); d = fromPole.pop(); toPole.push(d); hanoi(discs-1,aux, toPole, fromPole); }
Stacks
21
A Legend The Towers 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 three 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.
Stacks
22
Is the End of the World Approaching? • Problem complexity 2n • 64 gold discs • Given 1 move a second
Stacks
23