SlideShare a Scribd company logo
Data Structures
Stacks
Andres Mendez-Vazquez
May 6, 2015
1 / 130
Images/cinvestav-
Outline
1 Introduction
Example
ADT
2 Examples
Parentheses Matching
Towers of Hanoi
Chess
Method Invocation And Return
Method Invocation And Return
Rat In A Maze
3 Implementation
Derivation From ArrayLinearList
Derivation From Chain
4 Code Snippets
2 / 130
Images/cinvestav-
Introduction
Definition of a stack
It is a linear list where:
One end is called top
Other end is called bottom
Additionally, adds and removes are at the top end only.
3 / 130
Images/cinvestav-
Introduction
Definition of a stack
It is a linear list where:
One end is called top
Other end is called bottom
Additionally, adds and removes are at the top end only.
3 / 130
Images/cinvestav-
Introduction
Definition of a stack
It is a linear list where:
One end is called top
Other end is called bottom
Additionally, adds and removes are at the top end only.
3 / 130
Images/cinvestav-
Introduction
Definition of a stack
It is a linear list where:
One end is called top
Other end is called bottom
Additionally, adds and removes are at the top end only.
3 / 130
Images/cinvestav-
What is a stack?
First
Stores a set of elements in a particular order.
Second
Stack principle: LAST IN FIRST OUT = LIFO
Meaning
It means: the last element inserted is the first one to be removed
4 / 130
Images/cinvestav-
What is a stack?
First
Stores a set of elements in a particular order.
Second
Stack principle: LAST IN FIRST OUT = LIFO
Meaning
It means: the last element inserted is the first one to be removed
4 / 130
Images/cinvestav-
What is a stack?
First
Stores a set of elements in a particular order.
Second
Stack principle: LAST IN FIRST OUT = LIFO
Meaning
It means: the last element inserted is the first one to be removed
4 / 130
Images/cinvestav-
Outline
1 Introduction
Example
ADT
2 Examples
Parentheses Matching
Towers of Hanoi
Chess
Method Invocation And Return
Method Invocation And Return
Rat In A Maze
3 Implementation
Derivation From ArrayLinearList
Derivation From Chain
4 Code Snippets
5 / 130
Images/cinvestav-
Example in Real Life
Stack of Coins
6 / 130
Images/cinvestav-
Example
Insert the following items into a stack
List = {A, B, C, D, E}
7 / 130
Images/cinvestav-
Example
List = {A, B, C, D, E}
ABCDE
8 / 130
Images/cinvestav-
Example
List = {A, B, C, D, E}, Push A
ABCDE
9 / 130
Images/cinvestav-
Example
List = {B, C, D, E}
A
BCDE
10 / 130
Images/cinvestav-
Example
List = {B, C, D, E}, Push B
A
BCDE
11 / 130
Images/cinvestav-
Example
List = {C, D, E}
A
B
CDE
12 / 130
Images/cinvestav-
Example
List = {C, D, E}, Push C
A
B
CDE
13 / 130
Images/cinvestav-
Example
List = {D, E}
A
B
C
DE
14 / 130
Images/cinvestav-
Example
List = {D, E}, Push D
A
B
C
DE
15 / 130
Images/cinvestav-
Example
List = {E}
A
B
C
D
E
16 / 130
Images/cinvestav-
Example
List = {E}, Push E
A
B
C
D
E
17 / 130
Images/cinvestav-
Example
List = {E}, No space!!!Make Space
A
B
C
D
E
18 / 130
Images/cinvestav-
Example
List = {E}, Push E
A
B
C
D
E
19 / 130
Images/cinvestav-
Example
List = {}
A
B
C
D
E
20 / 130
Images/cinvestav-
Example
List = {}, Pop
A
B
C
D
E
21 / 130
Images/cinvestav-
Example
List = {E}, Pop
A
B
C
D
E
22 / 130
Images/cinvestav-
Example
List = {E,D}, Pop
A
B
C
DE
23 / 130
Images/cinvestav-
Example
List = {E,D,C}, Pop
A
B
CDE
24 / 130
Images/cinvestav-
Example
List = {E,D,C,B}, Pop
A
BCDE
25 / 130
Images/cinvestav-
Example
List = {E,D,C,B,A}
ABCDE
26 / 130
Images/cinvestav-
Outline
1 Introduction
Example
ADT
2 Examples
Parentheses Matching
Towers of Hanoi
Chess
Method Invocation And Return
Method Invocation And Return
Rat In A Maze
3 Implementation
Derivation From ArrayLinearList
Derivation From Chain
4 Code Snippets
27 / 130
Images/cinvestav-
Stacks ADT
Interface
p u b l i c i n t e r f a c e Stack<Item>
{
p u b l i c boolean empty ( ) ;
p u b l i c Item peek ( ) ;
p u b l i c void push ( Item TheObject ) ;
p u b l i c Item pop ( ) ;
}
28 / 130
Images/cinvestav-
Explanation of the ADT I
peek()
This method allows to look at the top of the stack without removing it!!!
For Example
29 / 130
Images/cinvestav-
Explanation of the ADT I
peek()
This method allows to look at the top of the stack without removing it!!!
For Example
A
B
C
D peek()
D
29 / 130
Images/cinvestav-
Explanation of the ADT II
pop()
This method allows to pop stuff from the top of the stack!!!
For Example
30 / 130
Images/cinvestav-
Explanation of the ADT II
pop()
This method allows to pop stuff from the top of the stack!!!
For Example
A
B
C
pop()
D
30 / 130
Images/cinvestav-
Explanation of the ADT III
push()
This method allows to push stuff to the top of the stack!!!
For Example
31 / 130
Images/cinvestav-
Explanation of the ADT III
push()
This method allows to push stuff to the top of the stack!!!
For Example
A
B
C
push( DD )
31 / 130
Images/cinvestav-
Explanation of the ADT III
empty()
This method allows to know if the stack is empty!!!
32 / 130
Images/cinvestav-
Stack Applications
Real life
Pile of books
Plate trays
More applications related to computer science
Program execution stack (You will know about this in OS or CA)
Evaluating expressions
33 / 130
Images/cinvestav-
Stack Applications
Real life
Pile of books
Plate trays
More applications related to computer science
Program execution stack (You will know about this in OS or CA)
Evaluating expressions
33 / 130
Images/cinvestav-
Stack Applications
Real life
Pile of books
Plate trays
More applications related to computer science
Program execution stack (You will know about this in OS or CA)
Evaluating expressions
33 / 130
Images/cinvestav-
Stack Applications
Real life
Pile of books
Plate trays
More applications related to computer science
Program execution stack (You will know about this in OS or CA)
Evaluating expressions
33 / 130
Images/cinvestav-
What do we do now?
First
Instead of going toward the implementations!!!
Why not examples?
1 Parentheses Matching
2 Towers Of Hanoi/Brahma
3 Switch Box Routing
4 Try-Throw-Catch in Java
5 Rat In A Maze
34 / 130
Images/cinvestav-
What do we do now?
First
Instead of going toward the implementations!!!
Why not examples?
1 Parentheses Matching
2 Towers Of Hanoi/Brahma
3 Switch Box Routing
4 Try-Throw-Catch in Java
5 Rat In A Maze
34 / 130
Images/cinvestav-
What do we do now?
First
Instead of going toward the implementations!!!
Why not examples?
1 Parentheses Matching
2 Towers Of Hanoi/Brahma
3 Switch Box Routing
4 Try-Throw-Catch in Java
5 Rat In A Maze
34 / 130
Images/cinvestav-
What do we do now?
First
Instead of going toward the implementations!!!
Why not examples?
1 Parentheses Matching
2 Towers Of Hanoi/Brahma
3 Switch Box Routing
4 Try-Throw-Catch in Java
5 Rat In A Maze
34 / 130
Images/cinvestav-
What do we do now?
First
Instead of going toward the implementations!!!
Why not examples?
1 Parentheses Matching
2 Towers Of Hanoi/Brahma
3 Switch Box Routing
4 Try-Throw-Catch in Java
5 Rat In A Maze
34 / 130
Images/cinvestav-
What do we do now?
First
Instead of going toward the implementations!!!
Why not examples?
1 Parentheses Matching
2 Towers Of Hanoi/Brahma
3 Switch Box Routing
4 Try-Throw-Catch in Java
5 Rat In A Maze
34 / 130
Images/cinvestav-
Outline
1 Introduction
Example
ADT
2 Examples
Parentheses Matching
Towers of Hanoi
Chess
Method Invocation And Return
Method Invocation And Return
Rat In A Maze
3 Implementation
Derivation From ArrayLinearList
Derivation From Chain
4 Code Snippets
35 / 130
Images/cinvestav-
Parentheses Matching
Example - Input
(((a+b)*c+d-e)/(f+g)-(h+j))
( ( ( a + b ) ∗ c + d − e ) / ...
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...
( f + g ) − ( h + j ) )
15 16 17 18 19 20 21 22 23 24 25 26
Output
Output pairs (u,v) such that the left parenthesis at position u is matched
with the right parenthesis at v.
Or
(2,6) (1,13) (15,19) (21,25) (0,26)
36 / 130
Images/cinvestav-
Parentheses Matching
Example - Input
(((a+b)*c+d-e)/(f+g)-(h+j))
( ( ( a + b ) ∗ c + d − e ) / ...
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...
( f + g ) − ( h + j ) )
15 16 17 18 19 20 21 22 23 24 25 26
Output
Output pairs (u,v) such that the left parenthesis at position u is matched
with the right parenthesis at v.
Or
(2,6) (1,13) (15,19) (21,25) (0,26)
36 / 130
Images/cinvestav-
Parentheses Matching
Example - Input
(((a+b)*c+d-e)/(f+g)-(h+j))
( ( ( a + b ) ∗ c + d − e ) / ...
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...
( f + g ) − ( h + j ) )
15 16 17 18 19 20 21 22 23 24 25 26
Output
Output pairs (u,v) such that the left parenthesis at position u is matched
with the right parenthesis at v.
Or
(2,6) (1,13) (15,19) (21,25) (0,26)
36 / 130
Images/cinvestav-
Wrong Matching
Input
(a+b))*((c+d)
Output
1 (0,4)
2 WRONG!!! Right parenthesis at 5 has no matching left parenthesis
3 (8,12)
4 WRONG!!! Left parenthesis at 7 has no matching right parenthesis
37 / 130
Images/cinvestav-
Wrong Matching
Input
(a+b))*((c+d)
Output
1 (0,4)
2 WRONG!!! Right parenthesis at 5 has no matching left parenthesis
3 (8,12)
4 WRONG!!! Left parenthesis at 7 has no matching right parenthesis
37 / 130
Images/cinvestav-
Wrong Matching
Input
(a+b))*((c+d)
Output
1 (0,4)
2 WRONG!!! Right parenthesis at 5 has no matching left parenthesis
3 (8,12)
4 WRONG!!! Left parenthesis at 7 has no matching right parenthesis
37 / 130
Images/cinvestav-
Wrong Matching
Input
(a+b))*((c+d)
Output
1 (0,4)
2 WRONG!!! Right parenthesis at 5 has no matching left parenthesis
3 (8,12)
4 WRONG!!! Left parenthesis at 7 has no matching right parenthesis
37 / 130
Images/cinvestav-
Wrong Matching
Input
(a+b))*((c+d)
Output
1 (0,4)
2 WRONG!!! Right parenthesis at 5 has no matching left parenthesis
3 (8,12)
4 WRONG!!! Left parenthesis at 7 has no matching right parenthesis
37 / 130
Images/cinvestav-
Wrong Matching
Input
(a+b))*((c+d)
Output
1 (0,4)
2 WRONG!!! Right parenthesis at 5 has no matching left parenthesis
3 (8,12)
4 WRONG!!! Left parenthesis at 7 has no matching right parenthesis
37 / 130
Images/cinvestav-
Developing a Recursive Solution I
First
What do we do? Ideas
Look at this
What if we have (a+b)?
38 / 130
Images/cinvestav-
Developing a Recursive Solution I
First
What do we do? Ideas
Look at this
What if we have (a+b)?
38 / 130
Images/cinvestav-
Initial Idea
boolean Rec-Paren(Chain List)
1 if (List.get(0)==’(’)
1 List.remove(0)
2 return Rec-Paren(List)
What else?
39 / 130
Images/cinvestav-
Initial Idea
boolean Rec-Paren(Chain List)
1 if (List.get(0)==’(’)
1 List.remove(0)
2 return Rec-Paren(List)
What else?
39 / 130
Images/cinvestav-
Initial Idea
boolean Rec-Paren(Chain List)
1 if (List.get(0)==’(’)
1 List.remove(0)
2 return Rec-Paren(List)
What else?
39 / 130
Images/cinvestav-
Initial Idea
boolean Rec-Paren(Chain List)
1 if (List.get(0)==’(’)
1 List.remove(0)
2 return Rec-Paren(List)
What else?
39 / 130
Images/cinvestav-
Next Case
Cont...
2. else if (List.get(0)==’[0-9]|[+-]’)
1 List.remove(0)
2 return Rec-Paren(List)
Last Step
3. else if (List.get(0)==’)’)
1 List.remove(0)
2 return true
3. else return false
40 / 130
Images/cinvestav-
Next Case
Cont...
2. else if (List.get(0)==’[0-9]|[+-]’)
1 List.remove(0)
2 return Rec-Paren(List)
Last Step
3. else if (List.get(0)==’)’)
1 List.remove(0)
2 return true
3. else return false
40 / 130
Images/cinvestav-
Next Case
Cont...
2. else if (List.get(0)==’[0-9]|[+-]’)
1 List.remove(0)
2 return Rec-Paren(List)
Last Step
3. else if (List.get(0)==’)’)
1 List.remove(0)
2 return true
3. else return false
40 / 130
Images/cinvestav-
Next Case
Cont...
2. else if (List.get(0)==’[0-9]|[+-]’)
1 List.remove(0)
2 return Rec-Paren(List)
Last Step
3. else if (List.get(0)==’)’)
1 List.remove(0)
2 return true
3. else return false
40 / 130
Images/cinvestav-
Next Case
Cont...
2. else if (List.get(0)==’[0-9]|[+-]’)
1 List.remove(0)
2 return Rec-Paren(List)
Last Step
3. else if (List.get(0)==’)’)
1 List.remove(0)
2 return true
3. else return false
40 / 130
Images/cinvestav-
Next Case
Cont...
2. else if (List.get(0)==’[0-9]|[+-]’)
1 List.remove(0)
2 return Rec-Paren(List)
Last Step
3. else if (List.get(0)==’)’)
1 List.remove(0)
2 return true
3. else return false
40 / 130
Images/cinvestav-
Next Case
Cont...
2. else if (List.get(0)==’[0-9]|[+-]’)
1 List.remove(0)
2 return Rec-Paren(List)
Last Step
3. else if (List.get(0)==’)’)
1 List.remove(0)
2 return true
3. else return false
40 / 130
Images/cinvestav-
Developing a Recursive Solution II
What if you have?
What if we have (a+b?
What about
What if we have a+b)?
41 / 130
Images/cinvestav-
Developing a Recursive Solution II
What if you have?
What if we have (a+b?
What about
What if we have a+b)?
41 / 130
Images/cinvestav-
This solution fails!!!
So, we need to send something down the recursion
What do we do? Ideas
42 / 130
Images/cinvestav-
What about...?
what if
We send down a flag!!
43 / 130
Images/cinvestav-
Thus
We need a flag to send down the recursion!!!
To tell the logic if we saw a left parenthesis
Ok
For simple problems fine!!! However...
44 / 130
Images/cinvestav-
Thus
We need a flag to send down the recursion!!!
To tell the logic if we saw a left parenthesis
Ok
For simple problems fine!!! However...
44 / 130
Images/cinvestav-
Then
For problems like these ones
((a+b)
Nope
It does not work
45 / 130
Images/cinvestav-
Then
For problems like these ones
((a+b)
Nope
It does not work
45 / 130
Images/cinvestav-
We need something more complex
A counter!!!
To see how many “(” we have seen down the recursion!!!
46 / 130
Images/cinvestav-
Recursive Solution - You assume a list of characters
p u b l i c s t a t i c boolean Balanced ( C h a i n L i n e a r L i s t L i s t ,
i n t Counter ){
i f ( L i s t . isEmpty ( ) ) { // Check empty
i f ( Counter == 0) // Check Counter
r e t u r n t r u e ;
e l s e
r e t u r n f a l s e ;}
i f ( L i s t . get (0)== ’ ( ’ ) // Case (
{
Counter++;
L i s t . remove ( 0 ) ;
r e t u r n Balanced ( L i s t , Counter ) ;
} e l s e i f ( L i s t . get (0)== ’ [0 −9]|[+ −] ’ ) // Case Number or −+
{
L i s t . remove ( 0 ) ;
r e t u r n Balanced ( L i s t , Counter ) ;
} e l s e i f ( L i s t . get (0)== ’ ) ’ ) // Case )
{
i f ( Counter > 0){
Counter −−;
L i s t . remove ( 0 ) ;
r e t u r n Balanced ( L i s t , Counter )
} e l s e r e t u r n f a l s e ;
} e l s e r e t u r n f a l s e
}
47 / 130
Images/cinvestav-
Can we simplify our code?
Yes
Using this memory container the STACK!!!
48 / 130
Images/cinvestav-
Before Anything Else
Did you notice something about my Chain during the recursion?
What?
49 / 130
Images/cinvestav-
Yepi!!!
Removing Elements
+( )CB
firstNode NULL
50 / 130
Images/cinvestav-
Yepi!!!
Removing Elements
+ )CB
firstNode NULL
51 / 130
Images/cinvestav-
Yepi!!!
Removing Elements
+ )C
firstNode NULL
52 / 130
Images/cinvestav-
So, we can simulate the recursion using what?
First a way to...
ITERATE
A memory storage
A Stack
So somebody?
Can give a process for it?
53 / 130
Images/cinvestav-
So, we can simulate the recursion using what?
First a way to...
ITERATE
A memory storage
A Stack
So somebody?
Can give a process for it?
53 / 130
Images/cinvestav-
So, we can simulate the recursion using what?
First a way to...
ITERATE
A memory storage
A Stack
So somebody?
Can give a process for it?
53 / 130
Images/cinvestav-
Iterative Solution - You assume a list of characters
p u b l i c s t a t i c boolean Balanced ( C h a i n L i n e a r L i s t L i s t ){
Stack I t = new Stack ( ) ;
i f ( L i s t . isEmpty ( ) )
r e t u r n t r u e
w h i l e ( ! L i s t . isEmpty ( ) ) { // Use a loop
i f ( L i s t . get (0)== ’ ( ’ )
{
I t . push ( L i s t . get ( 0 ) ) ;
L i s t . remove ( 0 ) ;
}
e l s e i f ( L i s t . get (0)== ’ [0 −9]|[+ −] ’ )
{ L i s t . remove (0) }
e l s e i f ( L i s t . get (0)== ’ ) ’ )
{
i f ( ! I t . empty ( ) )
I t . pop ( ) ;
e l s e
r e t u r n f a l s e ;
L i s t . remove ( 0 ) ; // Yes remove the
// l a s t ")"
}
i f ( I t . empty ( ) )
r e t u r n t r u e ;
r e t u r n f a l s e
}
54 / 130
Images/cinvestav-
Outline
1 Introduction
Example
ADT
2 Examples
Parentheses Matching
Towers of Hanoi
Chess
Method Invocation And Return
Method Invocation And Return
Rat In A Maze
3 Implementation
Derivation From ArrayLinearList
Derivation From Chain
4 Code Snippets
55 / 130
Images/cinvestav-
The Puzzle
The Leyend
There is a story about an Indian temple in Kashi Vishwanath which
contains a large room with three time-worn posts in it surrounded by
64 golden disks.
Something Notable
Brahmin priests, acting out the command of an ancient prophecy,
have been moving these disks, in accordance with the immutable rules
of the Brahma, since that time.
So
According to the legend, when the last move of the puzzle will be
completed, the world will end.
56 / 130
Images/cinvestav-
The Puzzle
The Leyend
There is a story about an Indian temple in Kashi Vishwanath which
contains a large room with three time-worn posts in it surrounded by
64 golden disks.
Something Notable
Brahmin priests, acting out the command of an ancient prophecy,
have been moving these disks, in accordance with the immutable rules
of the Brahma, since that time.
So
According to the legend, when the last move of the puzzle will be
completed, the world will end.
56 / 130
Images/cinvestav-
The Puzzle
The Leyend
There is a story about an Indian temple in Kashi Vishwanath which
contains a large room with three time-worn posts in it surrounded by
64 golden disks.
Something Notable
Brahmin priests, acting out the command of an ancient prophecy,
have been moving these disks, in accordance with the immutable rules
of the Brahma, since that time.
So
According to the legend, when the last move of the puzzle will be
completed, the world will end.
56 / 130
Images/cinvestav-
A simple example with 3 disks
The objective of the puzzle is to move the entire stack to the end rod
57 / 130
Images/cinvestav-
A simple example with 3 disks
The objective of the puzzle is to move the entire stack to the end rod
58 / 130
Images/cinvestav-
A simple example with 3 disks
The objective of the puzzle is to move the entire stack to the end rod
59 / 130
Images/cinvestav-
A simple example with 3 disks
The objective of the puzzle is to move the entire stack to the end rod
60 / 130
Images/cinvestav-
A simple example with 3 disks
The objective of the puzzle is to move the entire stack to the end rod
61 / 130
Images/cinvestav-
A simple example with 3 disks
The objective of the puzzle is to move the entire stack to the end rod
62 / 130
Images/cinvestav-
A simple example with 3 disks
The objective of the puzzle is to move the entire stack to the end rod
63 / 130
Images/cinvestav-
A simple example with 3 disks
The objective of the puzzle is to move the entire stack to the end rod
64 / 130
Images/cinvestav-
The Rules
First One
Only one disk can be moved at a time.
Second One
Each move consists of taking the upper disk from one of the stacks and
placing it on top of another stack i.e. a disk can only be moved if it is the
uppermost disk on a stack.
Third One
No disk may be placed on top of a smaller disk.
65 / 130
Images/cinvestav-
The Rules
First One
Only one disk can be moved at a time.
Second One
Each move consists of taking the upper disk from one of the stacks and
placing it on top of another stack i.e. a disk can only be moved if it is the
uppermost disk on a stack.
Third One
No disk may be placed on top of a smaller disk.
65 / 130
Images/cinvestav-
The Rules
First One
Only one disk can be moved at a time.
Second One
Each move consists of taking the upper disk from one of the stacks and
placing it on top of another stack i.e. a disk can only be moved if it is the
uppermost disk on a stack.
Third One
No disk may be placed on top of a smaller disk.
65 / 130
Images/cinvestav-
Properties
With Three disk
You can solve it in seven moves
Thus, the minimum number of moves required for n disks
2n
− 1 (1)
So how we solve the problem recursively?
Ideas?
66 / 130
Images/cinvestav-
Properties
With Three disk
You can solve it in seven moves
Thus, the minimum number of moves required for n disks
2n
− 1 (1)
So how we solve the problem recursively?
Ideas?
66 / 130
Images/cinvestav-
Properties
With Three disk
You can solve it in seven moves
Thus, the minimum number of moves required for n disks
2n
− 1 (1)
So how we solve the problem recursively?
Ideas?
66 / 130
Images/cinvestav-
Recursive Idea
Label the posts
67 / 130
Images/cinvestav-
Next
The other things
Let n be the total number of discs.
Number the discs from 1 (smallest, topmost) to n (largest,
bottommost)
How we solve this problem?
We can use the technique of “Divide and Conquer”
68 / 130
Images/cinvestav-
Next
The other things
Let n be the total number of discs.
Number the discs from 1 (smallest, topmost) to n (largest,
bottommost)
How we solve this problem?
We can use the technique of “Divide and Conquer”
68 / 130
Images/cinvestav-
Next
The other things
Let n be the total number of discs.
Number the discs from 1 (smallest, topmost) to n (largest,
bottommost)
How we solve this problem?
We can use the technique of “Divide and Conquer”
68 / 130
Images/cinvestav-
Divide and Conquer
Divide and Conquer
It is an important algorithm design paradigm based on multi-branched
recursion.
Divide
This phase of the algorithm works by recursively breaking down a
problem into two or more sub-problems of the same (or related) type.
The Conquer I
Then these subproblems become simple enough to be solved directly.
69 / 130
Images/cinvestav-
Divide and Conquer
Divide and Conquer
It is an important algorithm design paradigm based on multi-branched
recursion.
Divide
This phase of the algorithm works by recursively breaking down a
problem into two or more sub-problems of the same (or related) type.
The Conquer I
Then these subproblems become simple enough to be solved directly.
69 / 130
Images/cinvestav-
Divide and Conquer
Divide and Conquer
It is an important algorithm design paradigm based on multi-branched
recursion.
Divide
This phase of the algorithm works by recursively breaking down a
problem into two or more sub-problems of the same (or related) type.
The Conquer I
Then these subproblems become simple enough to be solved directly.
69 / 130
Images/cinvestav-
Divide and Conquer
The Conquer II
The solutions to the sub-problems are then combined to give a
solution to the original problem.
70 / 130
Images/cinvestav-
Question!!
First
What is the clever thing to do?
Example
71 / 130
Images/cinvestav-
A Simple Divide Phase
Move everything
The things that are in front of disk n.
In the previous case n = 3
Ok
How the recursion looks as simple logic steps?
72 / 130
Images/cinvestav-
A Simple Divide Phase
Move everything
The things that are in front of disk n.
In the previous case n = 3
Ok
How the recursion looks as simple logic steps?
72 / 130
Images/cinvestav-
The Initial Recursion
Logical Steps
To move n discs from tower A to tower C:
1 Move n − 1 discs from A to B using C as a temporary!!!
2 This leaves disc n alone on tower A move disc n from A to C.
3 Move n − 1 discs from B to C so they sit on disc n using A as
temporary!!!
73 / 130
Images/cinvestav-
The Initial Recursion
Logical Steps
To move n discs from tower A to tower C:
1 Move n − 1 discs from A to B using C as a temporary!!!
2 This leaves disc n alone on tower A move disc n from A to C.
3 Move n − 1 discs from B to C so they sit on disc n using A as
temporary!!!
73 / 130
Images/cinvestav-
The Initial Recursion
Logical Steps
To move n discs from tower A to tower C:
1 Move n − 1 discs from A to B using C as a temporary!!!
2 This leaves disc n alone on tower A move disc n from A to C.
3 Move n − 1 discs from B to C so they sit on disc n using A as
temporary!!!
73 / 130
Images/cinvestav-
The Initial Recursion
Logical Steps
To move n discs from tower A to tower C:
1 Move n − 1 discs from A to B using C as a temporary!!!
2 This leaves disc n alone on tower A move disc n from A to C.
3 Move n − 1 discs from B to C so they sit on disc n using A as
temporary!!!
73 / 130
Images/cinvestav-
Recursive Solution
Code
// Assume the l i s t i n A i s i n d e c r e a s i n g order
p u b l i c s t a t i c S t r i n g TH( i n t n , Char Origin ,
Char Destination ,
Char Temp){
S t r i n g r e s u l t ;
i f ( n = = 1){
r e t u r n "Move␣ Disk ␣"+n+"␣from␣"+ Or ig in +
"␣ to ␣" + D e s t i n a t i o n + "n" ;
}
r e s u l t = TH(n−1, Origin , Temp , D e s t i n a t i o n ) ;
r e s u l t+= "Move␣ Disk ␣"+n+"␣from␣"+ O ri gi n +
"␣ to ␣" + D e s t i n a t i o n + "n" ;
r e s u l t+= TH(n−1,Temp , Destination , Or ig i n ) ;
r e t u r n r e s u l t s ;
}
74 / 130
Images/cinvestav-
What do we need for the iterative solution?
Storage for the disks
Use one stack per tower!!!
A while loop to simulate the recursion
Doing What?
75 / 130
Images/cinvestav-
What do we need for the iterative solution?
Storage for the disks
Use one stack per tower!!!
A while loop to simulate the recursion
Doing What?
75 / 130
Images/cinvestav-
Simple Logic to the Iterative Version
Logic
A simple solution for the toy puzzle:
1 Alternate moves between the smallest piece and a non-smallest piece.
2 When moving the smallest piece, always move it to the next position
in the same direction.
3 If there is no tower position in the chosen direction, move the piece to
the opposite end, but then continue to move in the correct direction.
76 / 130
Images/cinvestav-
Simple Logic to the Iterative Version
Logic
A simple solution for the toy puzzle:
1 Alternate moves between the smallest piece and a non-smallest piece.
2 When moving the smallest piece, always move it to the next position
in the same direction.
3 If there is no tower position in the chosen direction, move the piece to
the opposite end, but then continue to move in the correct direction.
76 / 130
Images/cinvestav-
Simple Logic to the Iterative Version
Logic
A simple solution for the toy puzzle:
1 Alternate moves between the smallest piece and a non-smallest piece.
2 When moving the smallest piece, always move it to the next position
in the same direction.
3 If there is no tower position in the chosen direction, move the piece to
the opposite end, but then continue to move in the correct direction.
76 / 130
Images/cinvestav-
Simple Logic to the Iterative Version
Logic
A simple solution for the toy puzzle:
1 Alternate moves between the smallest piece and a non-smallest piece.
2 When moving the smallest piece, always move it to the next position
in the same direction.
3 If there is no tower position in the chosen direction, move the piece to
the opposite end, but then continue to move in the correct direction.
76 / 130
Images/cinvestav-
A simple example with 3 disks
The objective of the puzzle is to move the entire stack to the end rod
77 / 130
Images/cinvestav-
We have two cases
When there are n disks
n is even
When there are n disk
n is odd
Then a really simple solution involving 2n−1
− 1 moves
You have three stacks: A, B, C.
78 / 130
Images/cinvestav-
We have two cases
When there are n disks
n is even
When there are n disk
n is odd
Then a really simple solution involving 2n−1
− 1 moves
You have three stacks: A, B, C.
78 / 130
Images/cinvestav-
We have two cases
When there are n disks
n is even
When there are n disk
n is odd
Then a really simple solution involving 2n−1
− 1 moves
You have three stacks: A, B, C.
78 / 130
Images/cinvestav-
We have for n even
Use Circular moves
A =⇒ B =⇒ C =⇒ A (2)
79 / 130
Images/cinvestav-
We have for n odd
Use Circular Moves
A =⇒ C =⇒ B =⇒ A (3)
80 / 130
Images/cinvestav-
Process
IterativeHT using three stacks : towerA, towerB, towerC
1 for i = 1 to 2n−1
1 If (n%2 == 0)
1 Select the smallest disk at the top of the stacks
2 Move the smallest disk one position in the direction of the cyclic order
for even order.
3 Move the next largest disk to the only possible stack
2 else
1 Select the smallest disk at the top of the stacks
2 Move the smallest disk one position in the direction of the cyclic order
for odd order.
3 Move the next largest disk to the only possible stack
81 / 130
Images/cinvestav-
Process
IterativeHT using three stacks : towerA, towerB, towerC
1 for i = 1 to 2n−1
1 If (n%2 == 0)
1 Select the smallest disk at the top of the stacks
2 Move the smallest disk one position in the direction of the cyclic order
for even order.
3 Move the next largest disk to the only possible stack
2 else
1 Select the smallest disk at the top of the stacks
2 Move the smallest disk one position in the direction of the cyclic order
for odd order.
3 Move the next largest disk to the only possible stack
81 / 130
Images/cinvestav-
Process
IterativeHT using three stacks : towerA, towerB, towerC
1 for i = 1 to 2n−1
1 If (n%2 == 0)
1 Select the smallest disk at the top of the stacks
2 Move the smallest disk one position in the direction of the cyclic order
for even order.
3 Move the next largest disk to the only possible stack
2 else
1 Select the smallest disk at the top of the stacks
2 Move the smallest disk one position in the direction of the cyclic order
for odd order.
3 Move the next largest disk to the only possible stack
81 / 130
Images/cinvestav-
Process
IterativeHT using three stacks : towerA, towerB, towerC
1 for i = 1 to 2n−1
1 If (n%2 == 0)
1 Select the smallest disk at the top of the stacks
2 Move the smallest disk one position in the direction of the cyclic order
for even order.
3 Move the next largest disk to the only possible stack
2 else
1 Select the smallest disk at the top of the stacks
2 Move the smallest disk one position in the direction of the cyclic order
for odd order.
3 Move the next largest disk to the only possible stack
81 / 130
Images/cinvestav-
Process
IterativeHT using three stacks : towerA, towerB, towerC
1 for i = 1 to 2n−1
1 If (n%2 == 0)
1 Select the smallest disk at the top of the stacks
2 Move the smallest disk one position in the direction of the cyclic order
for even order.
3 Move the next largest disk to the only possible stack
2 else
1 Select the smallest disk at the top of the stacks
2 Move the smallest disk one position in the direction of the cyclic order
for odd order.
3 Move the next largest disk to the only possible stack
81 / 130
Images/cinvestav-
Process
IterativeHT using three stacks : towerA, towerB, towerC
1 for i = 1 to 2n−1
1 If (n%2 == 0)
1 Select the smallest disk at the top of the stacks
2 Move the smallest disk one position in the direction of the cyclic order
for even order.
3 Move the next largest disk to the only possible stack
2 else
1 Select the smallest disk at the top of the stacks
2 Move the smallest disk one position in the direction of the cyclic order
for odd order.
3 Move the next largest disk to the only possible stack
81 / 130
Images/cinvestav-
Process
IterativeHT using three stacks : towerA, towerB, towerC
1 for i = 1 to 2n−1
1 If (n%2 == 0)
1 Select the smallest disk at the top of the stacks
2 Move the smallest disk one position in the direction of the cyclic order
for even order.
3 Move the next largest disk to the only possible stack
2 else
1 Select the smallest disk at the top of the stacks
2 Move the smallest disk one position in the direction of the cyclic order
for odd order.
3 Move the next largest disk to the only possible stack
81 / 130
Images/cinvestav-
Process
IterativeHT using three stacks : towerA, towerB, towerC
1 for i = 1 to 2n−1
1 If (n%2 == 0)
1 Select the smallest disk at the top of the stacks
2 Move the smallest disk one position in the direction of the cyclic order
for even order.
3 Move the next largest disk to the only possible stack
2 else
1 Select the smallest disk at the top of the stacks
2 Move the smallest disk one position in the direction of the cyclic order
for odd order.
3 Move the next largest disk to the only possible stack
81 / 130
Images/cinvestav-
Process
IterativeHT using three stacks : towerA, towerB, towerC
1 for i = 1 to 2n−1
1 If (n%2 == 0)
1 Select the smallest disk at the top of the stacks
2 Move the smallest disk one position in the direction of the cyclic order
for even order.
3 Move the next largest disk to the only possible stack
2 else
1 Select the smallest disk at the top of the stacks
2 Move the smallest disk one position in the direction of the cyclic order
for odd order.
3 Move the next largest disk to the only possible stack
81 / 130
Images/cinvestav-
What about the Most Efficient Version?
You need a node state
1 Number of Disks
2 Origin Tower
3 Destination Tower
4 Temporary Tower
82 / 130
Images/cinvestav-
What about the Most Efficient Version?
You need a node state
1 Number of Disks
2 Origin Tower
3 Destination Tower
4 Temporary Tower
82 / 130
Images/cinvestav-
What about the Most Efficient Version?
You need a node state
1 Number of Disks
2 Origin Tower
3 Destination Tower
4 Temporary Tower
82 / 130
Images/cinvestav-
What about the Most Efficient Version?
You need a node state
1 Number of Disks
2 Origin Tower
3 Destination Tower
4 Temporary Tower
82 / 130
Images/cinvestav-
We have then the following logic procedure
Iterative-Hanoi(n)
1 let S be an stack
2 let Result be a empty string
3 S.push(Node(n, A, C, B, Result))
4 while S is not empty
5 v = S.pop()
6 if (v.n == 1)
7 print "Move one from v.Origin to v.Destination n"
8 else
9 S.push(Node(v.n-1, v.Temp, v.Destination, v.Origin))
10 S.push(Node(1, v.Origin, v.Destination, v.Temp))
11 S.push(Node(v.n-1,v.Origin, v.Temp, v.Destination))
83 / 130
Images/cinvestav-
We have then the following logic procedure
Iterative-Hanoi(n)
1 let S be an stack
2 let Result be a empty string
3 S.push(Node(n, A, C, B, Result))
4 while S is not empty
5 v = S.pop()
6 if (v.n == 1)
7 print "Move one from v.Origin to v.Destination n"
8 else
9 S.push(Node(v.n-1, v.Temp, v.Destination, v.Origin))
10 S.push(Node(1, v.Origin, v.Destination, v.Temp))
11 S.push(Node(v.n-1,v.Origin, v.Temp, v.Destination))
83 / 130
Images/cinvestav-
We have then the following logic procedure
Iterative-Hanoi(n)
1 let S be an stack
2 let Result be a empty string
3 S.push(Node(n, A, C, B, Result))
4 while S is not empty
5 v = S.pop()
6 if (v.n == 1)
7 print "Move one from v.Origin to v.Destination n"
8 else
9 S.push(Node(v.n-1, v.Temp, v.Destination, v.Origin))
10 S.push(Node(1, v.Origin, v.Destination, v.Temp))
11 S.push(Node(v.n-1,v.Origin, v.Temp, v.Destination))
83 / 130
Images/cinvestav-
We have then the following logic procedure
Iterative-Hanoi(n)
1 let S be an stack
2 let Result be a empty string
3 S.push(Node(n, A, C, B, Result))
4 while S is not empty
5 v = S.pop()
6 if (v.n == 1)
7 print "Move one from v.Origin to v.Destination n"
8 else
9 S.push(Node(v.n-1, v.Temp, v.Destination, v.Origin))
10 S.push(Node(1, v.Origin, v.Destination, v.Temp))
11 S.push(Node(v.n-1,v.Origin, v.Temp, v.Destination))
83 / 130
Images/cinvestav-
We have then the following logic procedure
Iterative-Hanoi(n)
1 let S be an stack
2 let Result be a empty string
3 S.push(Node(n, A, C, B, Result))
4 while S is not empty
5 v = S.pop()
6 if (v.n == 1)
7 print "Move one from v.Origin to v.Destination n"
8 else
9 S.push(Node(v.n-1, v.Temp, v.Destination, v.Origin))
10 S.push(Node(1, v.Origin, v.Destination, v.Temp))
11 S.push(Node(v.n-1,v.Origin, v.Temp, v.Destination))
83 / 130
Images/cinvestav-
We have then the following logic procedure
Iterative-Hanoi(n)
1 let S be an stack
2 let Result be a empty string
3 S.push(Node(n, A, C, B, Result))
4 while S is not empty
5 v = S.pop()
6 if (v.n == 1)
7 print "Move one from v.Origin to v.Destination n"
8 else
9 S.push(Node(v.n-1, v.Temp, v.Destination, v.Origin))
10 S.push(Node(1, v.Origin, v.Destination, v.Temp))
11 S.push(Node(v.n-1,v.Origin, v.Temp, v.Destination))
83 / 130
Images/cinvestav-
We have then the following logic procedure
Iterative-Hanoi(n)
1 let S be an stack
2 let Result be a empty string
3 S.push(Node(n, A, C, B, Result))
4 while S is not empty
5 v = S.pop()
6 if (v.n == 1)
7 print "Move one from v.Origin to v.Destination n"
8 else
9 S.push(Node(v.n-1, v.Temp, v.Destination, v.Origin))
10 S.push(Node(1, v.Origin, v.Destination, v.Temp))
11 S.push(Node(v.n-1,v.Origin, v.Temp, v.Destination))
83 / 130
Images/cinvestav-
We have then the following logic procedure
Iterative-Hanoi(n)
1 let S be an stack
2 let Result be a empty string
3 S.push(Node(n, A, C, B, Result))
4 while S is not empty
5 v = S.pop()
6 if (v.n == 1)
7 print "Move one from v.Origin to v.Destination n"
8 else
9 S.push(Node(v.n-1, v.Temp, v.Destination, v.Origin))
10 S.push(Node(1, v.Origin, v.Destination, v.Temp))
11 S.push(Node(v.n-1,v.Origin, v.Temp, v.Destination))
83 / 130
Images/cinvestav-
We have then the following logic procedure
Iterative-Hanoi(n)
1 let S be an stack
2 let Result be a empty string
3 S.push(Node(n, A, C, B, Result))
4 while S is not empty
5 v = S.pop()
6 if (v.n == 1)
7 print "Move one from v.Origin to v.Destination n"
8 else
9 S.push(Node(v.n-1, v.Temp, v.Destination, v.Origin))
10 S.push(Node(1, v.Origin, v.Destination, v.Temp))
11 S.push(Node(v.n-1,v.Origin, v.Temp, v.Destination))
83 / 130
Images/cinvestav-
We have then the following logic procedure
Iterative-Hanoi(n)
1 let S be an stack
2 let Result be a empty string
3 S.push(Node(n, A, C, B, Result))
4 while S is not empty
5 v = S.pop()
6 if (v.n == 1)
7 print "Move one from v.Origin to v.Destination n"
8 else
9 S.push(Node(v.n-1, v.Temp, v.Destination, v.Origin))
10 S.push(Node(1, v.Origin, v.Destination, v.Temp))
11 S.push(Node(v.n-1,v.Origin, v.Temp, v.Destination))
83 / 130
Images/cinvestav-
What about the Legend?
To solve the towers of Hanoi for 64 disks
We need ≈ 1.8 ∗ 1019 moves
With a computer making 109
moves/second
A computer would take about 570 years to complete.
At 1 disk move/min
The monks will take about 3.4 × 1013 years.
The sun will destroy the life on earth in 2.8 × 109.
84 / 130
Images/cinvestav-
What about the Legend?
To solve the towers of Hanoi for 64 disks
We need ≈ 1.8 ∗ 1019 moves
With a computer making 109
moves/second
A computer would take about 570 years to complete.
At 1 disk move/min
The monks will take about 3.4 × 1013 years.
The sun will destroy the life on earth in 2.8 × 109.
84 / 130
Images/cinvestav-
What about the Legend?
To solve the towers of Hanoi for 64 disks
We need ≈ 1.8 ∗ 1019 moves
With a computer making 109
moves/second
A computer would take about 570 years to complete.
At 1 disk move/min
The monks will take about 3.4 × 1013 years.
The sun will destroy the life on earth in 2.8 × 109.
84 / 130
Images/cinvestav-
Outline
1 Introduction
Example
ADT
2 Examples
Parentheses Matching
Towers of Hanoi
Chess
Method Invocation And Return
Method Invocation And Return
Rat In A Maze
3 Implementation
Derivation From ArrayLinearList
Derivation From Chain
4 Code Snippets
85 / 130
Images/cinvestav-
Chess
As in the Tower of Hanoi
It is possible to devise a massive search solution based in the actual state
of the chess board.
State 0
86 / 130
Images/cinvestav-
Chess
As in the Tower of Hanoi
It is possible to devise a massive search solution based in the actual state
of the chess board.
State 0
86 / 130
Images/cinvestav-
Then
Something Notable
If you put 1 penny for the first square, 2 for next, 4 for next, 8 for
next, and so on.
You have
$3.6 ∗ 1017 (federal budget ~ 2 ∗ 1012) .
87 / 130
Images/cinvestav-
Then
Something Notable
If you put 1 penny for the first square, 2 for next, 4 for next, 8 for
next, and so on.
You have
$3.6 ∗ 1017 (federal budget ~ 2 ∗ 1012) .
87 / 130
Images/cinvestav-
Outline
1 Introduction
Example
ADT
2 Examples
Parentheses Matching
Towers of Hanoi
Chess
Method Invocation And Return
Method Invocation And Return
Rat In A Maze
3 Implementation
Derivation From ArrayLinearList
Derivation From Chain
4 Code Snippets
88 / 130
Images/cinvestav-
Method Invocation And Return
We have stack in the memory system
89 / 130
Images/cinvestav-
Method Invocation And Return
We have stack in the memory system
90 / 130
Images/cinvestav-
Method Invocation And Return
We have stack in the memory system
91 / 130
Images/cinvestav-
Outline
1 Introduction
Example
ADT
2 Examples
Parentheses Matching
Towers of Hanoi
Chess
Method Invocation And Return
Method Invocation And Return
Rat In A Maze
3 Implementation
Derivation From ArrayLinearList
Derivation From Chain
4 Code Snippets
92 / 130
Images/cinvestav-
Try-Throw-Catch
Thus
1 When you enter a try block, push the address of this block on a stack.
2 When an exception is thrown, pop the try block that is at the top of
the stack (if the stack is empty, terminate).
3 If the popped try block has no matching catch block, go back to the
preceding step.
4 If the popped try block has a matching catch block, execute the
matching catch block.
93 / 130
Images/cinvestav-
Try-Throw-Catch
Thus
1 When you enter a try block, push the address of this block on a stack.
2 When an exception is thrown, pop the try block that is at the top of
the stack (if the stack is empty, terminate).
3 If the popped try block has no matching catch block, go back to the
preceding step.
4 If the popped try block has a matching catch block, execute the
matching catch block.
93 / 130
Images/cinvestav-
Try-Throw-Catch
Thus
1 When you enter a try block, push the address of this block on a stack.
2 When an exception is thrown, pop the try block that is at the top of
the stack (if the stack is empty, terminate).
3 If the popped try block has no matching catch block, go back to the
preceding step.
4 If the popped try block has a matching catch block, execute the
matching catch block.
93 / 130
Images/cinvestav-
Try-Throw-Catch
Thus
1 When you enter a try block, push the address of this block on a stack.
2 When an exception is thrown, pop the try block that is at the top of
the stack (if the stack is empty, terminate).
3 If the popped try block has no matching catch block, go back to the
preceding step.
4 If the popped try block has a matching catch block, execute the
matching catch block.
93 / 130
Images/cinvestav-
Outline
1 Introduction
Example
ADT
2 Examples
Parentheses Matching
Towers of Hanoi
Chess
Method Invocation And Return
Method Invocation And Return
Rat In A Maze
3 Implementation
Derivation From ArrayLinearList
Derivation From Chain
4 Code Snippets
94 / 130
Images/cinvestav-
Rat In A Maze
Example
95 / 130
Images/cinvestav-
Rat In A Maze
Example
Move order is: right, down, left, up
Block positions to avoid revisit.
96 / 130
Images/cinvestav-
Rat In A Maze
Example
97 / 130
Images/cinvestav-
Rat In A Maze
Example
Move backward until we reach a square from which a forward move is
possible.
98 / 130
Images/cinvestav-
Rat In A Maze
Example
Move backward until we reach a square from which a forward move is
possible.
99 / 130
Images/cinvestav-
Rat In A Maze
Example
MOVE DOWN
100 / 130
Images/cinvestav-
Rat In A Maze
Example
MOVE LEFT
101 / 130
Images/cinvestav-
Rat In A Maze
Example

MOVE DOWN
102 / 130
Images/cinvestav-
Rat In A Maze
Example

Move backward until we reach a square from which a forward move is
possible.
103 / 130
Images/cinvestav-
Outline
1 Introduction
Example
ADT
2 Examples
Parentheses Matching
Towers of Hanoi
Chess
Method Invocation And Return
Method Invocation And Return
Rat In A Maze
3 Implementation
Derivation From ArrayLinearList
Derivation From Chain
4 Code Snippets
104 / 130
Images/cinvestav-
Derivation From ArrayLinearList
We can do the following
Stack top is either left end or right end of linear list
For any possible top
empty() =⇒ isEmpty()
O(1) time
peek() =⇒ get(0) or get(size() - 1)
O(1) time
105 / 130
Images/cinvestav-
Derivation From ArrayLinearList
We can do the following
Stack top is either left end or right end of linear list
For any possible top
empty() =⇒ isEmpty()
O(1) time
peek() =⇒ get(0) or get(size() - 1)
O(1) time
105 / 130
Images/cinvestav-
Derivation From ArrayLinearList
We can do the following
Stack top is either left end or right end of linear list
For any possible top
empty() =⇒ isEmpty()
O(1) time
peek() =⇒ get(0) or get(size() - 1)
O(1) time
105 / 130
Images/cinvestav-
Derivation From ArrayLinearList
We can do the following
Stack top is either left end or right end of linear list
For any possible top
empty() =⇒ isEmpty()
O(1) time
peek() =⇒ get(0) or get(size() - 1)
O(1) time
105 / 130
Images/cinvestav-
Derivation From ArrayLinearList
We can do the following
Stack top is either left end or right end of linear list
For any possible top
empty() =⇒ isEmpty()
O(1) time
peek() =⇒ get(0) or get(size() - 1)
O(1) time
105 / 130
Images/cinvestav-
Derivation From ArrayLinearList
When top is left end of linear list
push(theObject) =⇒ add(0, theObject)
O(size) time
pop() =⇒ remove(0)
O(size) time
106 / 130
Images/cinvestav-
Derivation From ArrayLinearList
When top is left end of linear list
push(theObject) =⇒ add(0, theObject)
O(size) time
pop() =⇒ remove(0)
O(size) time
106 / 130
Images/cinvestav-
Derivation From ArrayLinearList
When top is left end of linear list
push(theObject) =⇒ add(0, theObject)
O(size) time
pop() =⇒ remove(0)
O(size) time
106 / 130
Images/cinvestav-
Derivation From ArrayLinearList
When top is left end of linear list
push(theObject) =⇒ add(0, theObject)
O(size) time
pop() =⇒ remove(0)
O(size) time
106 / 130
Images/cinvestav-
Derivation From ArrayLinearList
When top is right end of linear list
For any possible top
push(theObject) =⇒ add(size(), theObject)
O(1) time
pop() =⇒ remove(size()-1)
O(1) time
107 / 130
Images/cinvestav-
Derivation From ArrayLinearList
When top is right end of linear list
For any possible top
push(theObject) =⇒ add(size(), theObject)
O(1) time
pop() =⇒ remove(size()-1)
O(1) time
107 / 130
Images/cinvestav-
Derivation From ArrayLinearList
When top is right end of linear list
For any possible top
push(theObject) =⇒ add(size(), theObject)
O(1) time
pop() =⇒ remove(size()-1)
O(1) time
107 / 130
Images/cinvestav-
Derivation From ArrayLinearList
When top is right end of linear list
For any possible top
push(theObject) =⇒ add(size(), theObject)
O(1) time
pop() =⇒ remove(size()-1)
O(1) time
107 / 130
Images/cinvestav-
Derivation From ArrayLinearList
When top is right end of linear list
For any possible top
push(theObject) =⇒ add(size(), theObject)
O(1) time
pop() =⇒ remove(size()-1)
O(1) time
107 / 130
Images/cinvestav-
Thus
The Moral of the Story
You must use the right end of list as top of stack
That is way
108 / 130
Images/cinvestav-
Thus
The Moral of the Story
You must use the right end of list as top of stack
That is way
STACK
DATA
TEXT
HEAP
0
High Memory
Growing Directions
108 / 130
Images/cinvestav-
Outline
1 Introduction
Example
ADT
2 Examples
Parentheses Matching
Towers of Hanoi
Chess
Method Invocation And Return
Method Invocation And Return
Rat In A Maze
3 Implementation
Derivation From ArrayLinearList
Derivation From Chain
4 Code Snippets
109 / 130
Images/cinvestav-
Derivation from a Chain
Stack top is either left end or right end of linear list
CA EDB
firstNode NULL
Thus
empty() =⇒ isEmpty()
O(1) time
110 / 130
Images/cinvestav-
Derivation from a Chain
Stack top is either left end or right end of linear list
CA EDB
firstNode NULL
Thus
empty() =⇒ isEmpty()
O(1) time
110 / 130
Images/cinvestav-
Derivation from a Chain
Stack top is either left end or right end of linear list
CA EDB
firstNode NULL
Thus
empty() =⇒ isEmpty()
O(1) time
110 / 130
Images/cinvestav-
Derivation from a Chain
When top is left end of linear list
CA EDB
firstNode NULL
Thus
peek() =⇒ get(0)
O(1) time
push(theObject) =⇒ add(0, theObject)
O(1) time
pop() =⇒ remove(0)
O(1) time
111 / 130
Images/cinvestav-
Derivation from a Chain
When top is left end of linear list
CA EDB
firstNode NULL
Thus
peek() =⇒ get(0)
O(1) time
push(theObject) =⇒ add(0, theObject)
O(1) time
pop() =⇒ remove(0)
O(1) time
111 / 130
Images/cinvestav-
Derivation from a Chain
When top is left end of linear list
CA EDB
firstNode NULL
Thus
peek() =⇒ get(0)
O(1) time
push(theObject) =⇒ add(0, theObject)
O(1) time
pop() =⇒ remove(0)
O(1) time
111 / 130
Images/cinvestav-
Derivation from a Chain
When top is left end of linear list
CA EDB
firstNode NULL
Thus
peek() =⇒ get(0)
O(1) time
push(theObject) =⇒ add(0, theObject)
O(1) time
pop() =⇒ remove(0)
O(1) time
111 / 130
Images/cinvestav-
Derivation from a Chain
When top is left end of linear list
CA EDB
firstNode NULL
Thus
peek() =⇒ get(0)
O(1) time
push(theObject) =⇒ add(0, theObject)
O(1) time
pop() =⇒ remove(0)
O(1) time
111 / 130
Images/cinvestav-
Derivation from a Chain
When top is left end of linear list
CA EDB
firstNode NULL
Thus
peek() =⇒ get(0)
O(1) time
push(theObject) =⇒ add(0, theObject)
O(1) time
pop() =⇒ remove(0)
O(1) time
111 / 130
Images/cinvestav-
Derivation from a Chain
When top is left end of linear list
CA EDB
firstNode NULL
Thus
peek() =⇒ get(0)
O(1) time
push(theObject) =⇒ add(0, theObject)
O(1) time
pop() =⇒ remove(0)
O(1) time
111 / 130
Images/cinvestav-
Derivation from a Chain
When top is left end of linear list
CA EDB
firstNode NULL
Thus
peek() =⇒ get(size()-1)
O(size) time
push(theObject) =⇒ add(size(), theObject)
O(size) time
pop() =⇒ remove(size()-1)
O(size) time
112 / 130
Images/cinvestav-
Derivation from a Chain
When top is left end of linear list
CA EDB
firstNode NULL
Thus
peek() =⇒ get(size()-1)
O(size) time
push(theObject) =⇒ add(size(), theObject)
O(size) time
pop() =⇒ remove(size()-1)
O(size) time
112 / 130
Images/cinvestav-
Derivation from a Chain
When top is left end of linear list
CA EDB
firstNode NULL
Thus
peek() =⇒ get(size()-1)
O(size) time
push(theObject) =⇒ add(size(), theObject)
O(size) time
pop() =⇒ remove(size()-1)
O(size) time
112 / 130
Images/cinvestav-
Derivation from a Chain
When top is left end of linear list
CA EDB
firstNode NULL
Thus
peek() =⇒ get(size()-1)
O(size) time
push(theObject) =⇒ add(size(), theObject)
O(size) time
pop() =⇒ remove(size()-1)
O(size) time
112 / 130
Images/cinvestav-
Derivation from a Chain
When top is left end of linear list
CA EDB
firstNode NULL
Thus
peek() =⇒ get(size()-1)
O(size) time
push(theObject) =⇒ add(size(), theObject)
O(size) time
pop() =⇒ remove(size()-1)
O(size) time
112 / 130
Images/cinvestav-
Derivation from a Chain
When top is left end of linear list
CA EDB
firstNode NULL
Thus
peek() =⇒ get(size()-1)
O(size) time
push(theObject) =⇒ add(size(), theObject)
O(size) time
pop() =⇒ remove(size()-1)
O(size) time
112 / 130
Images/cinvestav-
Derivation from a Chain
When top is left end of linear list
CA EDB
firstNode NULL
Thus
peek() =⇒ get(size()-1)
O(size) time
push(theObject) =⇒ add(size(), theObject)
O(size) time
pop() =⇒ remove(size()-1)
O(size) time
112 / 130
Images/cinvestav-
Thus
The Moral of the Story
You must use the left end of list as top of stack
113 / 130
Images/cinvestav-
Derive From ArrayLinearList
Code
package MyStack ;
import java . u t i l . ∗ ; // I t has stack e x c e p t i o n
p u b l i c c l a s s DerivedArrayStack extends
A r r a y L i n e a r L i s t <Item>
{
// c o n s t r u c t o r s come here
// Stack i n t e r f a c e methods come here
}
114 / 130
Images/cinvestav-
Derive From ArrayLinearList
Constructors
/∗∗ c r e a t e a stack with the given i n i t i a l
∗ c a p a c i t y ∗/
p u b l i c DerivedArrayStack ( i n t i n i t i a l C a p a c i t y )
{ super ( i n i t i a l C a p a c i t y ) ; }
/∗∗ c r e a t e a stack with i n i t i a l c a p a c i t y 10 ∗/
p u b l i c DerivedArrayStack ()
{ t h i s ( 1 0 ) ; }
115 / 130
Images/cinvestav-
empty() And peek()
Code
p u b l i c boolean empty ()
{ r e t u r n isEmpty ( ) ; }
p u b l i c Object peek ()
{
i f ( empty ( ) )
throw new EmptyStackException ( ) ;
r e t u r n get ( s i z e () − 1 ) ;
}
116 / 130
Images/cinvestav-
push(theObject) And pop()
Code
p u b l i c void push ( Object theElement )
{add ( s i z e ( ) , theElement ) ; }
p u b l i c Object pop ()
{
i f ( empty ( ) )
throw new EmptyStackException ( ) ;
r e t u r n remove ( s i z e () − 1 ) ;
}
117 / 130
Images/cinvestav-
The Pros
The merits of deriving from ArrayLinearList
Code for derived class is quite simple and easy to develop.
Code is expected to require little debugging.
Code for other stack implementations such as a linked
implementation are easily obtained.
Just replace extends ArrayLinearList with extends Chain.
For efficiency reasons we must also make changes to use the left end of
the list as the stack top rather than the right end.
118 / 130
Images/cinvestav-
The Pros
The merits of deriving from ArrayLinearList
Code for derived class is quite simple and easy to develop.
Code is expected to require little debugging.
Code for other stack implementations such as a linked
implementation are easily obtained.
Just replace extends ArrayLinearList with extends Chain.
For efficiency reasons we must also make changes to use the left end of
the list as the stack top rather than the right end.
118 / 130
Images/cinvestav-
The Pros
The merits of deriving from ArrayLinearList
Code for derived class is quite simple and easy to develop.
Code is expected to require little debugging.
Code for other stack implementations such as a linked
implementation are easily obtained.
Just replace extends ArrayLinearList with extends Chain.
For efficiency reasons we must also make changes to use the left end of
the list as the stack top rather than the right end.
118 / 130
Images/cinvestav-
The Pros
The merits of deriving from ArrayLinearList
Code for derived class is quite simple and easy to develop.
Code is expected to require little debugging.
Code for other stack implementations such as a linked
implementation are easily obtained.
Just replace extends ArrayLinearList with extends Chain.
For efficiency reasons we must also make changes to use the left end of
the list as the stack top rather than the right end.
118 / 130
Images/cinvestav-
The Pros
The merits of deriving from ArrayLinearList
Code for derived class is quite simple and easy to develop.
Code is expected to require little debugging.
Code for other stack implementations such as a linked
implementation are easily obtained.
Just replace extends ArrayLinearList with extends Chain.
For efficiency reasons we must also make changes to use the left end of
the list as the stack top rather than the right end.
118 / 130
Images/cinvestav-
The Cons
Then
All public methods of ArrayLinearList are performed following the
stack structure:
get(0) . . . get bottom element
remove(5)... pop
add(3, x) ... push
So we do not have a true stack implementation.
We must override undesired methods.
119 / 130
Images/cinvestav-
The Cons
Then
All public methods of ArrayLinearList are performed following the
stack structure:
get(0) . . . get bottom element
remove(5)... pop
add(3, x) ... push
So we do not have a true stack implementation.
We must override undesired methods.
119 / 130
Images/cinvestav-
The Cons
Then
All public methods of ArrayLinearList are performed following the
stack structure:
get(0) . . . get bottom element
remove(5)... pop
add(3, x) ... push
So we do not have a true stack implementation.
We must override undesired methods.
119 / 130
Images/cinvestav-
The Cons
Then
All public methods of ArrayLinearList are performed following the
stack structure:
get(0) . . . get bottom element
remove(5)... pop
add(3, x) ... push
So we do not have a true stack implementation.
We must override undesired methods.
119 / 130
Images/cinvestav-
The Cons
Then
All public methods of ArrayLinearList are performed following the
stack structure:
get(0) . . . get bottom element
remove(5)... pop
add(3, x) ... push
So we do not have a true stack implementation.
We must override undesired methods.
119 / 130
Images/cinvestav-
The Cons
Unnecessary work is done by the code.
Examples
Example I
peek() verifies that the stack is not empty before get is invoked.
The index check done by get is, therefore, not needed.
Example II
add(size(), theElement) does an index check and a for loop that is
not entered.
Neither is needed.
120 / 130
Images/cinvestav-
The Cons
Unnecessary work is done by the code.
Examples
Example I
peek() verifies that the stack is not empty before get is invoked.
The index check done by get is, therefore, not needed.
Example II
add(size(), theElement) does an index check and a for loop that is
not entered.
Neither is needed.
120 / 130
Images/cinvestav-
The Cons
Unnecessary work is done by the code.
Examples
Example I
peek() verifies that the stack is not empty before get is invoked.
The index check done by get is, therefore, not needed.
Example II
add(size(), theElement) does an index check and a for loop that is
not entered.
Neither is needed.
120 / 130
Images/cinvestav-
The Cons
Unnecessary work is done by the code.
Examples
Example I
peek() verifies that the stack is not empty before get is invoked.
The index check done by get is, therefore, not needed.
Example II
add(size(), theElement) does an index check and a for loop that is
not entered.
Neither is needed.
120 / 130
Images/cinvestav-
The Cons
Unnecessary work is done by the code.
Examples
Example I
peek() verifies that the stack is not empty before get is invoked.
The index check done by get is, therefore, not needed.
Example II
add(size(), theElement) does an index check and a for loop that is
not entered.
Neither is needed.
120 / 130
Images/cinvestav-
Then
Thus
So the derived code runs slower than necessary.
121 / 130
Images/cinvestav-
Moral of the Story
First
Code developed from scratch will run faster but will take more time (cost)
to develop.
Second
Tradeoff between software development cost and performance.
Third
Tradeoff between time to market and performance.
Fourth
It could be easy to develop the code first and later refine it to improve
performance.
122 / 130
Images/cinvestav-
Moral of the Story
First
Code developed from scratch will run faster but will take more time (cost)
to develop.
Second
Tradeoff between software development cost and performance.
Third
Tradeoff between time to market and performance.
Fourth
It could be easy to develop the code first and later refine it to improve
performance.
122 / 130
Images/cinvestav-
Moral of the Story
First
Code developed from scratch will run faster but will take more time (cost)
to develop.
Second
Tradeoff between software development cost and performance.
Third
Tradeoff between time to market and performance.
Fourth
It could be easy to develop the code first and later refine it to improve
performance.
122 / 130
Images/cinvestav-
Moral of the Story
First
Code developed from scratch will run faster but will take more time (cost)
to develop.
Second
Tradeoff between software development cost and performance.
Third
Tradeoff between time to market and performance.
Fourth
It could be easy to develop the code first and later refine it to improve
performance.
122 / 130
Images/cinvestav-
Example
A slow pop
1 if (empty())
2 throw new EmptyStackException();
3 return remove(size() - 1);
Faster Code
1 try {return remove(size() - 1);}
2 catch(IndexOutOfBoundsException e)
3 {throw new EmptyStackException();}
123 / 130
Images/cinvestav-
Example
A slow pop
1 if (empty())
2 throw new EmptyStackException();
3 return remove(size() - 1);
Faster Code
1 try {return remove(size() - 1);}
2 catch(IndexOutOfBoundsException e)
3 {throw new EmptyStackException();}
123 / 130
Images/cinvestav-
Example
A slow pop
1 if (empty())
2 throw new EmptyStackException();
3 return remove(size() - 1);
Faster Code
1 try {return remove(size() - 1);}
2 catch(IndexOutOfBoundsException e)
3 {throw new EmptyStackException();}
123 / 130
Images/cinvestav-
Example
A slow pop
1 if (empty())
2 throw new EmptyStackException();
3 return remove(size() - 1);
Faster Code
1 try {return remove(size() - 1);}
2 catch(IndexOutOfBoundsException e)
3 {throw new EmptyStackException();}
123 / 130
Images/cinvestav-
Example
A slow pop
1 if (empty())
2 throw new EmptyStackException();
3 return remove(size() - 1);
Faster Code
1 try {return remove(size() - 1);}
2 catch(IndexOutOfBoundsException e)
3 {throw new EmptyStackException();}
123 / 130
Images/cinvestav-
Example
A slow pop
1 if (empty())
2 throw new EmptyStackException();
3 return remove(size() - 1);
Faster Code
1 try {return remove(size() - 1);}
2 catch(IndexOutOfBoundsException e)
3 {throw new EmptyStackException();}
123 / 130
Images/cinvestav-
Code From Scratch
First
Use a 1D array stack whose data type is Item.
same as using array element in ArrayLinearList
Second
Use an int variable top.
Stack elements are in stack[0:top].
Top element is in stack[top].
Bottom element is in stack[0].
Stack is empty iff top = -1.
Number of elements in stack is top+1.
124 / 130
Images/cinvestav-
Code From Scratch
First
Use a 1D array stack whose data type is Item.
same as using array element in ArrayLinearList
Second
Use an int variable top.
Stack elements are in stack[0:top].
Top element is in stack[top].
Bottom element is in stack[0].
Stack is empty iff top = -1.
Number of elements in stack is top+1.
124 / 130
Images/cinvestav-
Code From Scratch
First
Use a 1D array stack whose data type is Item.
same as using array element in ArrayLinearList
Second
Use an int variable top.
Stack elements are in stack[0:top].
Top element is in stack[top].
Bottom element is in stack[0].
Stack is empty iff top = -1.
Number of elements in stack is top+1.
124 / 130
Images/cinvestav-
Code From Scratch
First
Use a 1D array stack whose data type is Item.
same as using array element in ArrayLinearList
Second
Use an int variable top.
Stack elements are in stack[0:top].
Top element is in stack[top].
Bottom element is in stack[0].
Stack is empty iff top = -1.
Number of elements in stack is top+1.
124 / 130
Images/cinvestav-
Code From Scratch
First
Use a 1D array stack whose data type is Item.
same as using array element in ArrayLinearList
Second
Use an int variable top.
Stack elements are in stack[0:top].
Top element is in stack[top].
Bottom element is in stack[0].
Stack is empty iff top = -1.
Number of elements in stack is top+1.
124 / 130
Images/cinvestav-
Code From Scratch
First
Use a 1D array stack whose data type is Item.
same as using array element in ArrayLinearList
Second
Use an int variable top.
Stack elements are in stack[0:top].
Top element is in stack[top].
Bottom element is in stack[0].
Stack is empty iff top = -1.
Number of elements in stack is top+1.
124 / 130
Images/cinvestav-
Code From Scratch
First
Use a 1D array stack whose data type is Item.
same as using array element in ArrayLinearList
Second
Use an int variable top.
Stack elements are in stack[0:top].
Top element is in stack[top].
Bottom element is in stack[0].
Stack is empty iff top = -1.
Number of elements in stack is top+1.
124 / 130
Images/cinvestav-
Code From Scratch
First
Use a 1D array stack whose data type is Item.
same as using array element in ArrayLinearList
Second
Use an int variable top.
Stack elements are in stack[0:top].
Top element is in stack[top].
Bottom element is in stack[0].
Stack is empty iff top = -1.
Number of elements in stack is top+1.
124 / 130
Images/cinvestav-
Code From Scratch
Data Memember
package Stack ;
import java . u t i l . EmptyStackException ;
import u t i l i t i e s . ∗ ;
p u b l i c c l a s s ArrayStack<Item>
implements Stack<Item>
{
// data members
i n t top ; // c u r r e n t top of stack
Item [ ] stack ; // element a r r a y
// Etc
}
125 / 130
Images/cinvestav-
Constructors
Code
p u b l i c ArrayStack ( i n t i n i t i a l C a p a c i t y )
{
i f ( i n i t i a l C a p a c i t y < 1)
throw new I l l e g a l A r g u m e n t E x c e p t i o n
( " i n i t i a l C a p a c i t y ␣must␣be␣>=␣1" ) ;
t h i s . stack = ( Item [ ] ) new Object [ i n i t i a l C a p a c i t y ] ;
top = −1;
}
p u b l i c ArrayStack ()
{ t h i s ( 1 0 ) ; }
126 / 130
Images/cinvestav-
Push(...)
Code
p u b l i c void push ( Object theElement )
{
// i n c r e a s e a r r a y s i z e i f n e c e s s a r y
i f ( top == stack . le ngth − 1)
stack = ChangeArrayLength . changeLength1D
( stack , 2 ∗ stack . l ength ) ;
// put theElement at the top of the stack
stack[++top ] = theElement ;
}
Thus
127 / 130
Images/cinvestav-
Pop()
Code
p u b l i c Item pop ()
{
i f ( empty ( ) )
throw new EmptyStackException ( ) ;
Object topElement = stack [ top ] ;
stack [ top −−] = n u l l ; // enable garbage c o l l e c t i o n
r e t u r n topElement ;
}
Thus
128 / 130
Images/cinvestav-
Actually
We have the following
java.util.Stack
It derives from java.util.Vector.
java.util.Vector is an array implementation of a linear list.
129 / 130
Images/cinvestav-
Performance of 500,000 pop, push, and peek operations
We have
Class 500,000
DerivedArrayStack 0.38 s
Scratch Array Stack 0.22 s
DerivedArrayStackWithCatch 0.33 s
DerivedLinkedStack 3.20 s
Scratch LinkedStack 2.96 s
130 / 130

More Related Content

What's hot

05 queues
05 queues05 queues
05 queues
Rajan Gautam
 
Functional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Functional Core and Imperative Shell - Game of Life Example - Haskell and ScalaFunctional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Functional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Philip Schwarz
 
Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Sequence and Traverse - Part 2
Sequence and Traverse - Part 2
Philip Schwarz
 
Monad Transformers - Part 1
Monad Transformers - Part 1Monad Transformers - Part 1
Monad Transformers - Part 1
Philip Schwarz
 
Abstracting over the Monad yielded by a for comprehension and its generators
Abstracting over the Monad yielded by a for comprehension and its generatorsAbstracting over the Monad yielded by a for comprehension and its generators
Abstracting over the Monad yielded by a for comprehension and its generators
Philip Schwarz
 
Contravariant functors in scala
Contravariant functors in scalaContravariant functors in scala
Contravariant functors in scala
Piotr Paradziński
 
Functor Composition
Functor CompositionFunctor Composition
Functor Composition
Philip Schwarz
 
Monoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and CatsMonoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and Cats
Philip Schwarz
 
Top down and botttom up 2 LATEST.
Top down     and botttom up 2 LATEST.Top down     and botttom up 2 LATEST.
Top down and botttom up 2 LATEST.
Gerwin Ocsena
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
Hermann Hueck
 
Monads do not Compose
Monads do not ComposeMonads do not Compose
Monads do not Compose
Philip Schwarz
 
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Philip Schwarz
 
Addendum to ‘Monads do not Compose’
Addendum to ‘Monads do not Compose’ Addendum to ‘Monads do not Compose’
Addendum to ‘Monads do not Compose’
Philip Schwarz
 
Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1
Philip Schwarz
 
Scala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data TypeScala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data Type
Philip Schwarz
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and Cats
Philip Schwarz
 
Top down parsing(sid) (1)
Top down parsing(sid) (1)Top down parsing(sid) (1)
Top down parsing(sid) (1)
Siddhesh Pange
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
Intro C# Book
 

What's hot (20)

Arrays
ArraysArrays
Arrays
 
05 queues
05 queues05 queues
05 queues
 
Functional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Functional Core and Imperative Shell - Game of Life Example - Haskell and ScalaFunctional Core and Imperative Shell - Game of Life Example - Haskell and Scala
Functional Core and Imperative Shell - Game of Life Example - Haskell and Scala
 
Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Sequence and Traverse - Part 2
Sequence and Traverse - Part 2
 
Monad Transformers - Part 1
Monad Transformers - Part 1Monad Transformers - Part 1
Monad Transformers - Part 1
 
Abstracting over the Monad yielded by a for comprehension and its generators
Abstracting over the Monad yielded by a for comprehension and its generatorsAbstracting over the Monad yielded by a for comprehension and its generators
Abstracting over the Monad yielded by a for comprehension and its generators
 
C programming slide c05
C programming slide c05C programming slide c05
C programming slide c05
 
Contravariant functors in scala
Contravariant functors in scalaContravariant functors in scala
Contravariant functors in scala
 
Functor Composition
Functor CompositionFunctor Composition
Functor Composition
 
Monoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and CatsMonoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and Cats
 
Top down and botttom up 2 LATEST.
Top down     and botttom up 2 LATEST.Top down     and botttom up 2 LATEST.
Top down and botttom up 2 LATEST.
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
 
Monads do not Compose
Monads do not ComposeMonads do not Compose
Monads do not Compose
 
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
 
Addendum to ‘Monads do not Compose’
Addendum to ‘Monads do not Compose’ Addendum to ‘Monads do not Compose’
Addendum to ‘Monads do not Compose’
 
Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1
 
Scala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data TypeScala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data Type
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and Cats
 
Top down parsing(sid) (1)
Top down parsing(sid) (1)Top down parsing(sid) (1)
Top down parsing(sid) (1)
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 

Viewers also liked

23 Matrix Algorithms
23 Matrix Algorithms23 Matrix Algorithms
23 Matrix Algorithms
Andres Mendez-Vazquez
 
01 Machine Learning Introduction
01 Machine Learning Introduction 01 Machine Learning Introduction
01 Machine Learning Introduction
Andres Mendez-Vazquez
 
11 Machine Learning Important Issues in Machine Learning
11 Machine Learning Important Issues in Machine Learning11 Machine Learning Important Issues in Machine Learning
11 Machine Learning Important Issues in Machine Learning
Andres Mendez-Vazquez
 
Drainage
DrainageDrainage
Drainage
Ansh Jindal
 
07 Machine Learning - Expectation Maximization
07 Machine Learning - Expectation Maximization07 Machine Learning - Expectation Maximization
07 Machine Learning - Expectation Maximization
Andres Mendez-Vazquez
 
Work energy power 2 reading assignment -revision 2
Work energy power 2 reading assignment -revision 2Work energy power 2 reading assignment -revision 2
Work energy power 2 reading assignment -revision 2sashrilisdi
 
Preparation Data Structures 05 chain linear_list
Preparation Data Structures 05 chain linear_listPreparation Data Structures 05 chain linear_list
Preparation Data Structures 05 chain linear_list
Andres Mendez-Vazquez
 
03 Probability Review for Analysis of Algorithms
03 Probability Review for Analysis of Algorithms03 Probability Review for Analysis of Algorithms
03 Probability Review for Analysis of Algorithms
Andres Mendez-Vazquez
 
13 Machine Learning Supervised Decision Trees
13 Machine Learning Supervised Decision Trees13 Machine Learning Supervised Decision Trees
13 Machine Learning Supervised Decision Trees
Andres Mendez-Vazquez
 
Periodic table (1)
Periodic table (1)Periodic table (1)
Periodic table (1)jghopwood
 
Preparation Data Structures 10 trees
Preparation Data Structures 10 treesPreparation Data Structures 10 trees
Preparation Data Structures 10 trees
Andres Mendez-Vazquez
 
What's the Matter?
What's the Matter?What's the Matter?
What's the Matter?
Stephen Taylor
 
26 Computational Geometry
26 Computational Geometry26 Computational Geometry
26 Computational Geometry
Andres Mendez-Vazquez
 
31 Machine Learning Unsupervised Cluster Validity
31 Machine Learning Unsupervised Cluster Validity31 Machine Learning Unsupervised Cluster Validity
31 Machine Learning Unsupervised Cluster Validity
Andres Mendez-Vazquez
 
15 B-Trees
15 B-Trees15 B-Trees
23 Machine Learning Feature Generation
23 Machine Learning Feature Generation23 Machine Learning Feature Generation
23 Machine Learning Feature Generation
Andres Mendez-Vazquez
 

Viewers also liked (20)

23 Matrix Algorithms
23 Matrix Algorithms23 Matrix Algorithms
23 Matrix Algorithms
 
01 Machine Learning Introduction
01 Machine Learning Introduction 01 Machine Learning Introduction
01 Machine Learning Introduction
 
Waves
WavesWaves
Waves
 
11 Machine Learning Important Issues in Machine Learning
11 Machine Learning Important Issues in Machine Learning11 Machine Learning Important Issues in Machine Learning
11 Machine Learning Important Issues in Machine Learning
 
Drainage
DrainageDrainage
Drainage
 
07 Machine Learning - Expectation Maximization
07 Machine Learning - Expectation Maximization07 Machine Learning - Expectation Maximization
07 Machine Learning - Expectation Maximization
 
Work energy power 2 reading assignment -revision 2
Work energy power 2 reading assignment -revision 2Work energy power 2 reading assignment -revision 2
Work energy power 2 reading assignment -revision 2
 
Preparation Data Structures 05 chain linear_list
Preparation Data Structures 05 chain linear_listPreparation Data Structures 05 chain linear_list
Preparation Data Structures 05 chain linear_list
 
03 Probability Review for Analysis of Algorithms
03 Probability Review for Analysis of Algorithms03 Probability Review for Analysis of Algorithms
03 Probability Review for Analysis of Algorithms
 
13 Machine Learning Supervised Decision Trees
13 Machine Learning Supervised Decision Trees13 Machine Learning Supervised Decision Trees
13 Machine Learning Supervised Decision Trees
 
Periodic table (1)
Periodic table (1)Periodic table (1)
Periodic table (1)
 
Preparation Data Structures 10 trees
Preparation Data Structures 10 treesPreparation Data Structures 10 trees
Preparation Data Structures 10 trees
 
What's the Matter?
What's the Matter?What's the Matter?
What's the Matter?
 
26 Computational Geometry
26 Computational Geometry26 Computational Geometry
26 Computational Geometry
 
31 Machine Learning Unsupervised Cluster Validity
31 Machine Learning Unsupervised Cluster Validity31 Machine Learning Unsupervised Cluster Validity
31 Machine Learning Unsupervised Cluster Validity
 
15 B-Trees
15 B-Trees15 B-Trees
15 B-Trees
 
F1
F1F1
F1
 
Force resolution force
Force resolution forceForce resolution force
Force resolution force
 
Force resultant force
Force resultant forceForce resultant force
Force resultant force
 
23 Machine Learning Feature Generation
23 Machine Learning Feature Generation23 Machine Learning Feature Generation
23 Machine Learning Feature Generation
 

Similar to Preparation Data Structures 07 stacks

Stack and queue
Stack and queueStack and queue
Stack and queue
Shakila Mahjabin
 
RxJava In Baby Steps
RxJava In Baby StepsRxJava In Baby Steps
RxJava In Baby Steps
Annyce Davis
 
Stacks.ppt
Stacks.pptStacks.ppt
Stacks.ppt
OliverKane3
 
Stacks.ppt
Stacks.pptStacks.ppt
Stacks.ppt
OliverKane3
 
Circular queues
Circular queuesCircular queues
Circular queues
Ssankett Negi
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
A. S. M. Shafi
 
Stack_Application_Infix_Prefix.pptx
Stack_Application_Infix_Prefix.pptxStack_Application_Infix_Prefix.pptx
Stack_Application_Infix_Prefix.pptx
sandeep54552
 
Arduino programming of ML-style in ATS
Arduino programming of ML-style in ATSArduino programming of ML-style in ATS
Arduino programming of ML-style in ATS
Kiwamu Okabe
 
Python cheatsheat.pdf
Python cheatsheat.pdfPython cheatsheat.pdf
Python cheatsheat.pdf
HimoZZZ
 
Computer notes - Josephus Problem
Computer notes - Josephus ProblemComputer notes - Josephus Problem
Computer notes - Josephus Problem
ecomputernotes
 
computer notes - Data Structures - 5
computer notes - Data Structures - 5computer notes - Data Structures - 5
computer notes - Data Structures - 5ecomputernotes
 
Oscon 2010 Specs talk
Oscon 2010 Specs talkOscon 2010 Specs talk
Oscon 2010 Specs talk
Eric Torreborre
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arraystameemyousaf
 
1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf
afgt2012
 
Datastage real time scenario
Datastage real time scenarioDatastage real time scenario
Datastage real time scenario
Naresh Bala
 
C1 - Insertion Sort
C1 - Insertion SortC1 - Insertion Sort
C1 - Insertion Sort
Juan Zamora, MSc. MBA
 
Fun with Kotlin
Fun with KotlinFun with Kotlin
Fun with Kotlin
Egor Andreevich
 
Gssl
GsslGssl
Gssl
ncct
 
My lecture infix-to-postfix
My lecture infix-to-postfixMy lecture infix-to-postfix
My lecture infix-to-postfixSenthil Kumar
 
queues.pptx
queues.pptxqueues.pptx
queues.pptx
Aadilhussain65
 

Similar to Preparation Data Structures 07 stacks (20)

Stack and queue
Stack and queueStack and queue
Stack and queue
 
RxJava In Baby Steps
RxJava In Baby StepsRxJava In Baby Steps
RxJava In Baby Steps
 
Stacks.ppt
Stacks.pptStacks.ppt
Stacks.ppt
 
Stacks.ppt
Stacks.pptStacks.ppt
Stacks.ppt
 
Circular queues
Circular queuesCircular queues
Circular queues
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
 
Stack_Application_Infix_Prefix.pptx
Stack_Application_Infix_Prefix.pptxStack_Application_Infix_Prefix.pptx
Stack_Application_Infix_Prefix.pptx
 
Arduino programming of ML-style in ATS
Arduino programming of ML-style in ATSArduino programming of ML-style in ATS
Arduino programming of ML-style in ATS
 
Python cheatsheat.pdf
Python cheatsheat.pdfPython cheatsheat.pdf
Python cheatsheat.pdf
 
Computer notes - Josephus Problem
Computer notes - Josephus ProblemComputer notes - Josephus Problem
Computer notes - Josephus Problem
 
computer notes - Data Structures - 5
computer notes - Data Structures - 5computer notes - Data Structures - 5
computer notes - Data Structures - 5
 
Oscon 2010 Specs talk
Oscon 2010 Specs talkOscon 2010 Specs talk
Oscon 2010 Specs talk
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays
 
1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf
 
Datastage real time scenario
Datastage real time scenarioDatastage real time scenario
Datastage real time scenario
 
C1 - Insertion Sort
C1 - Insertion SortC1 - Insertion Sort
C1 - Insertion Sort
 
Fun with Kotlin
Fun with KotlinFun with Kotlin
Fun with Kotlin
 
Gssl
GsslGssl
Gssl
 
My lecture infix-to-postfix
My lecture infix-to-postfixMy lecture infix-to-postfix
My lecture infix-to-postfix
 
queues.pptx
queues.pptxqueues.pptx
queues.pptx
 

More from Andres Mendez-Vazquez

2.03 bayesian estimation
2.03 bayesian estimation2.03 bayesian estimation
2.03 bayesian estimation
Andres Mendez-Vazquez
 
05 linear transformations
05 linear transformations05 linear transformations
05 linear transformations
Andres Mendez-Vazquez
 
01.04 orthonormal basis_eigen_vectors
01.04 orthonormal basis_eigen_vectors01.04 orthonormal basis_eigen_vectors
01.04 orthonormal basis_eigen_vectors
Andres Mendez-Vazquez
 
01.03 squared matrices_and_other_issues
01.03 squared matrices_and_other_issues01.03 squared matrices_and_other_issues
01.03 squared matrices_and_other_issues
Andres Mendez-Vazquez
 
01.02 linear equations
01.02 linear equations01.02 linear equations
01.02 linear equations
Andres Mendez-Vazquez
 
01.01 vector spaces
01.01 vector spaces01.01 vector spaces
01.01 vector spaces
Andres Mendez-Vazquez
 
06 recurrent neural_networks
06 recurrent neural_networks06 recurrent neural_networks
06 recurrent neural_networks
Andres Mendez-Vazquez
 
05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiation05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiation
Andres Mendez-Vazquez
 
Zetta global
Zetta globalZetta global
Zetta global
Andres Mendez-Vazquez
 
01 Introduction to Neural Networks and Deep Learning
01 Introduction to Neural Networks and Deep Learning01 Introduction to Neural Networks and Deep Learning
01 Introduction to Neural Networks and Deep Learning
Andres Mendez-Vazquez
 
25 introduction reinforcement_learning
25 introduction reinforcement_learning25 introduction reinforcement_learning
25 introduction reinforcement_learning
Andres Mendez-Vazquez
 
Neural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning SyllabusNeural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning Syllabus
Andres Mendez-Vazquez
 
Introduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabusIntroduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabus
Andres Mendez-Vazquez
 
Ideas 09 22_2018
Ideas 09 22_2018Ideas 09 22_2018
Ideas 09 22_2018
Andres Mendez-Vazquez
 
Ideas about a Bachelor in Machine Learning/Data Sciences
Ideas about a Bachelor in Machine Learning/Data SciencesIdeas about a Bachelor in Machine Learning/Data Sciences
Ideas about a Bachelor in Machine Learning/Data Sciences
Andres Mendez-Vazquez
 
Analysis of Algorithms Syllabus
Analysis of Algorithms  SyllabusAnalysis of Algorithms  Syllabus
Analysis of Algorithms Syllabus
Andres Mendez-Vazquez
 
20 k-means, k-center, k-meoids and variations
20 k-means, k-center, k-meoids and variations20 k-means, k-center, k-meoids and variations
20 k-means, k-center, k-meoids and variations
Andres Mendez-Vazquez
 
18.1 combining models
18.1 combining models18.1 combining models
18.1 combining models
Andres Mendez-Vazquez
 
17 vapnik chervonenkis dimension
17 vapnik chervonenkis dimension17 vapnik chervonenkis dimension
17 vapnik chervonenkis dimension
Andres Mendez-Vazquez
 
A basic introduction to learning
A basic introduction to learningA basic introduction to learning
A basic introduction to learning
Andres Mendez-Vazquez
 

More from Andres Mendez-Vazquez (20)

2.03 bayesian estimation
2.03 bayesian estimation2.03 bayesian estimation
2.03 bayesian estimation
 
05 linear transformations
05 linear transformations05 linear transformations
05 linear transformations
 
01.04 orthonormal basis_eigen_vectors
01.04 orthonormal basis_eigen_vectors01.04 orthonormal basis_eigen_vectors
01.04 orthonormal basis_eigen_vectors
 
01.03 squared matrices_and_other_issues
01.03 squared matrices_and_other_issues01.03 squared matrices_and_other_issues
01.03 squared matrices_and_other_issues
 
01.02 linear equations
01.02 linear equations01.02 linear equations
01.02 linear equations
 
01.01 vector spaces
01.01 vector spaces01.01 vector spaces
01.01 vector spaces
 
06 recurrent neural_networks
06 recurrent neural_networks06 recurrent neural_networks
06 recurrent neural_networks
 
05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiation05 backpropagation automatic_differentiation
05 backpropagation automatic_differentiation
 
Zetta global
Zetta globalZetta global
Zetta global
 
01 Introduction to Neural Networks and Deep Learning
01 Introduction to Neural Networks and Deep Learning01 Introduction to Neural Networks and Deep Learning
01 Introduction to Neural Networks and Deep Learning
 
25 introduction reinforcement_learning
25 introduction reinforcement_learning25 introduction reinforcement_learning
25 introduction reinforcement_learning
 
Neural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning SyllabusNeural Networks and Deep Learning Syllabus
Neural Networks and Deep Learning Syllabus
 
Introduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabusIntroduction to artificial_intelligence_syllabus
Introduction to artificial_intelligence_syllabus
 
Ideas 09 22_2018
Ideas 09 22_2018Ideas 09 22_2018
Ideas 09 22_2018
 
Ideas about a Bachelor in Machine Learning/Data Sciences
Ideas about a Bachelor in Machine Learning/Data SciencesIdeas about a Bachelor in Machine Learning/Data Sciences
Ideas about a Bachelor in Machine Learning/Data Sciences
 
Analysis of Algorithms Syllabus
Analysis of Algorithms  SyllabusAnalysis of Algorithms  Syllabus
Analysis of Algorithms Syllabus
 
20 k-means, k-center, k-meoids and variations
20 k-means, k-center, k-meoids and variations20 k-means, k-center, k-meoids and variations
20 k-means, k-center, k-meoids and variations
 
18.1 combining models
18.1 combining models18.1 combining models
18.1 combining models
 
17 vapnik chervonenkis dimension
17 vapnik chervonenkis dimension17 vapnik chervonenkis dimension
17 vapnik chervonenkis dimension
 
A basic introduction to learning
A basic introduction to learningA basic introduction to learning
A basic introduction to learning
 

Recently uploaded

Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 

Recently uploaded (20)

Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 

Preparation Data Structures 07 stacks

  • 2. Images/cinvestav- Outline 1 Introduction Example ADT 2 Examples Parentheses Matching Towers of Hanoi Chess Method Invocation And Return Method Invocation And Return Rat In A Maze 3 Implementation Derivation From ArrayLinearList Derivation From Chain 4 Code Snippets 2 / 130
  • 3. Images/cinvestav- Introduction Definition of a stack It is a linear list where: One end is called top Other end is called bottom Additionally, adds and removes are at the top end only. 3 / 130
  • 4. Images/cinvestav- Introduction Definition of a stack It is a linear list where: One end is called top Other end is called bottom Additionally, adds and removes are at the top end only. 3 / 130
  • 5. Images/cinvestav- Introduction Definition of a stack It is a linear list where: One end is called top Other end is called bottom Additionally, adds and removes are at the top end only. 3 / 130
  • 6. Images/cinvestav- Introduction Definition of a stack It is a linear list where: One end is called top Other end is called bottom Additionally, adds and removes are at the top end only. 3 / 130
  • 7. Images/cinvestav- What is a stack? First Stores a set of elements in a particular order. Second Stack principle: LAST IN FIRST OUT = LIFO Meaning It means: the last element inserted is the first one to be removed 4 / 130
  • 8. Images/cinvestav- What is a stack? First Stores a set of elements in a particular order. Second Stack principle: LAST IN FIRST OUT = LIFO Meaning It means: the last element inserted is the first one to be removed 4 / 130
  • 9. Images/cinvestav- What is a stack? First Stores a set of elements in a particular order. Second Stack principle: LAST IN FIRST OUT = LIFO Meaning It means: the last element inserted is the first one to be removed 4 / 130
  • 10. Images/cinvestav- Outline 1 Introduction Example ADT 2 Examples Parentheses Matching Towers of Hanoi Chess Method Invocation And Return Method Invocation And Return Rat In A Maze 3 Implementation Derivation From ArrayLinearList Derivation From Chain 4 Code Snippets 5 / 130
  • 11. Images/cinvestav- Example in Real Life Stack of Coins 6 / 130
  • 12. Images/cinvestav- Example Insert the following items into a stack List = {A, B, C, D, E} 7 / 130
  • 13. Images/cinvestav- Example List = {A, B, C, D, E} ABCDE 8 / 130
  • 14. Images/cinvestav- Example List = {A, B, C, D, E}, Push A ABCDE 9 / 130
  • 15. Images/cinvestav- Example List = {B, C, D, E} A BCDE 10 / 130
  • 16. Images/cinvestav- Example List = {B, C, D, E}, Push B A BCDE 11 / 130
  • 17. Images/cinvestav- Example List = {C, D, E} A B CDE 12 / 130
  • 18. Images/cinvestav- Example List = {C, D, E}, Push C A B CDE 13 / 130
  • 19. Images/cinvestav- Example List = {D, E} A B C DE 14 / 130
  • 20. Images/cinvestav- Example List = {D, E}, Push D A B C DE 15 / 130
  • 22. Images/cinvestav- Example List = {E}, Push E A B C D E 17 / 130
  • 23. Images/cinvestav- Example List = {E}, No space!!!Make Space A B C D E 18 / 130
  • 24. Images/cinvestav- Example List = {E}, Push E A B C D E 19 / 130
  • 26. Images/cinvestav- Example List = {}, Pop A B C D E 21 / 130
  • 27. Images/cinvestav- Example List = {E}, Pop A B C D E 22 / 130
  • 32. Images/cinvestav- Outline 1 Introduction Example ADT 2 Examples Parentheses Matching Towers of Hanoi Chess Method Invocation And Return Method Invocation And Return Rat In A Maze 3 Implementation Derivation From ArrayLinearList Derivation From Chain 4 Code Snippets 27 / 130
  • 33. Images/cinvestav- Stacks ADT Interface p u b l i c i n t e r f a c e Stack<Item> { p u b l i c boolean empty ( ) ; p u b l i c Item peek ( ) ; p u b l i c void push ( Item TheObject ) ; p u b l i c Item pop ( ) ; } 28 / 130
  • 34. Images/cinvestav- Explanation of the ADT I peek() This method allows to look at the top of the stack without removing it!!! For Example 29 / 130
  • 35. Images/cinvestav- Explanation of the ADT I peek() This method allows to look at the top of the stack without removing it!!! For Example A B C D peek() D 29 / 130
  • 36. Images/cinvestav- Explanation of the ADT II pop() This method allows to pop stuff from the top of the stack!!! For Example 30 / 130
  • 37. Images/cinvestav- Explanation of the ADT II pop() This method allows to pop stuff from the top of the stack!!! For Example A B C pop() D 30 / 130
  • 38. Images/cinvestav- Explanation of the ADT III push() This method allows to push stuff to the top of the stack!!! For Example 31 / 130
  • 39. Images/cinvestav- Explanation of the ADT III push() This method allows to push stuff to the top of the stack!!! For Example A B C push( DD ) 31 / 130
  • 40. Images/cinvestav- Explanation of the ADT III empty() This method allows to know if the stack is empty!!! 32 / 130
  • 41. Images/cinvestav- Stack Applications Real life Pile of books Plate trays More applications related to computer science Program execution stack (You will know about this in OS or CA) Evaluating expressions 33 / 130
  • 42. Images/cinvestav- Stack Applications Real life Pile of books Plate trays More applications related to computer science Program execution stack (You will know about this in OS or CA) Evaluating expressions 33 / 130
  • 43. Images/cinvestav- Stack Applications Real life Pile of books Plate trays More applications related to computer science Program execution stack (You will know about this in OS or CA) Evaluating expressions 33 / 130
  • 44. Images/cinvestav- Stack Applications Real life Pile of books Plate trays More applications related to computer science Program execution stack (You will know about this in OS or CA) Evaluating expressions 33 / 130
  • 45. Images/cinvestav- What do we do now? First Instead of going toward the implementations!!! Why not examples? 1 Parentheses Matching 2 Towers Of Hanoi/Brahma 3 Switch Box Routing 4 Try-Throw-Catch in Java 5 Rat In A Maze 34 / 130
  • 46. Images/cinvestav- What do we do now? First Instead of going toward the implementations!!! Why not examples? 1 Parentheses Matching 2 Towers Of Hanoi/Brahma 3 Switch Box Routing 4 Try-Throw-Catch in Java 5 Rat In A Maze 34 / 130
  • 47. Images/cinvestav- What do we do now? First Instead of going toward the implementations!!! Why not examples? 1 Parentheses Matching 2 Towers Of Hanoi/Brahma 3 Switch Box Routing 4 Try-Throw-Catch in Java 5 Rat In A Maze 34 / 130
  • 48. Images/cinvestav- What do we do now? First Instead of going toward the implementations!!! Why not examples? 1 Parentheses Matching 2 Towers Of Hanoi/Brahma 3 Switch Box Routing 4 Try-Throw-Catch in Java 5 Rat In A Maze 34 / 130
  • 49. Images/cinvestav- What do we do now? First Instead of going toward the implementations!!! Why not examples? 1 Parentheses Matching 2 Towers Of Hanoi/Brahma 3 Switch Box Routing 4 Try-Throw-Catch in Java 5 Rat In A Maze 34 / 130
  • 50. Images/cinvestav- What do we do now? First Instead of going toward the implementations!!! Why not examples? 1 Parentheses Matching 2 Towers Of Hanoi/Brahma 3 Switch Box Routing 4 Try-Throw-Catch in Java 5 Rat In A Maze 34 / 130
  • 51. Images/cinvestav- Outline 1 Introduction Example ADT 2 Examples Parentheses Matching Towers of Hanoi Chess Method Invocation And Return Method Invocation And Return Rat In A Maze 3 Implementation Derivation From ArrayLinearList Derivation From Chain 4 Code Snippets 35 / 130
  • 52. Images/cinvestav- Parentheses Matching Example - Input (((a+b)*c+d-e)/(f+g)-(h+j)) ( ( ( a + b ) ∗ c + d − e ) / ... 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ... ( f + g ) − ( h + j ) ) 15 16 17 18 19 20 21 22 23 24 25 26 Output Output pairs (u,v) such that the left parenthesis at position u is matched with the right parenthesis at v. Or (2,6) (1,13) (15,19) (21,25) (0,26) 36 / 130
  • 53. Images/cinvestav- Parentheses Matching Example - Input (((a+b)*c+d-e)/(f+g)-(h+j)) ( ( ( a + b ) ∗ c + d − e ) / ... 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ... ( f + g ) − ( h + j ) ) 15 16 17 18 19 20 21 22 23 24 25 26 Output Output pairs (u,v) such that the left parenthesis at position u is matched with the right parenthesis at v. Or (2,6) (1,13) (15,19) (21,25) (0,26) 36 / 130
  • 54. Images/cinvestav- Parentheses Matching Example - Input (((a+b)*c+d-e)/(f+g)-(h+j)) ( ( ( a + b ) ∗ c + d − e ) / ... 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ... ( f + g ) − ( h + j ) ) 15 16 17 18 19 20 21 22 23 24 25 26 Output Output pairs (u,v) such that the left parenthesis at position u is matched with the right parenthesis at v. Or (2,6) (1,13) (15,19) (21,25) (0,26) 36 / 130
  • 55. Images/cinvestav- Wrong Matching Input (a+b))*((c+d) Output 1 (0,4) 2 WRONG!!! Right parenthesis at 5 has no matching left parenthesis 3 (8,12) 4 WRONG!!! Left parenthesis at 7 has no matching right parenthesis 37 / 130
  • 56. Images/cinvestav- Wrong Matching Input (a+b))*((c+d) Output 1 (0,4) 2 WRONG!!! Right parenthesis at 5 has no matching left parenthesis 3 (8,12) 4 WRONG!!! Left parenthesis at 7 has no matching right parenthesis 37 / 130
  • 57. Images/cinvestav- Wrong Matching Input (a+b))*((c+d) Output 1 (0,4) 2 WRONG!!! Right parenthesis at 5 has no matching left parenthesis 3 (8,12) 4 WRONG!!! Left parenthesis at 7 has no matching right parenthesis 37 / 130
  • 58. Images/cinvestav- Wrong Matching Input (a+b))*((c+d) Output 1 (0,4) 2 WRONG!!! Right parenthesis at 5 has no matching left parenthesis 3 (8,12) 4 WRONG!!! Left parenthesis at 7 has no matching right parenthesis 37 / 130
  • 59. Images/cinvestav- Wrong Matching Input (a+b))*((c+d) Output 1 (0,4) 2 WRONG!!! Right parenthesis at 5 has no matching left parenthesis 3 (8,12) 4 WRONG!!! Left parenthesis at 7 has no matching right parenthesis 37 / 130
  • 60. Images/cinvestav- Wrong Matching Input (a+b))*((c+d) Output 1 (0,4) 2 WRONG!!! Right parenthesis at 5 has no matching left parenthesis 3 (8,12) 4 WRONG!!! Left parenthesis at 7 has no matching right parenthesis 37 / 130
  • 61. Images/cinvestav- Developing a Recursive Solution I First What do we do? Ideas Look at this What if we have (a+b)? 38 / 130
  • 62. Images/cinvestav- Developing a Recursive Solution I First What do we do? Ideas Look at this What if we have (a+b)? 38 / 130
  • 63. Images/cinvestav- Initial Idea boolean Rec-Paren(Chain List) 1 if (List.get(0)==’(’) 1 List.remove(0) 2 return Rec-Paren(List) What else? 39 / 130
  • 64. Images/cinvestav- Initial Idea boolean Rec-Paren(Chain List) 1 if (List.get(0)==’(’) 1 List.remove(0) 2 return Rec-Paren(List) What else? 39 / 130
  • 65. Images/cinvestav- Initial Idea boolean Rec-Paren(Chain List) 1 if (List.get(0)==’(’) 1 List.remove(0) 2 return Rec-Paren(List) What else? 39 / 130
  • 66. Images/cinvestav- Initial Idea boolean Rec-Paren(Chain List) 1 if (List.get(0)==’(’) 1 List.remove(0) 2 return Rec-Paren(List) What else? 39 / 130
  • 67. Images/cinvestav- Next Case Cont... 2. else if (List.get(0)==’[0-9]|[+-]’) 1 List.remove(0) 2 return Rec-Paren(List) Last Step 3. else if (List.get(0)==’)’) 1 List.remove(0) 2 return true 3. else return false 40 / 130
  • 68. Images/cinvestav- Next Case Cont... 2. else if (List.get(0)==’[0-9]|[+-]’) 1 List.remove(0) 2 return Rec-Paren(List) Last Step 3. else if (List.get(0)==’)’) 1 List.remove(0) 2 return true 3. else return false 40 / 130
  • 69. Images/cinvestav- Next Case Cont... 2. else if (List.get(0)==’[0-9]|[+-]’) 1 List.remove(0) 2 return Rec-Paren(List) Last Step 3. else if (List.get(0)==’)’) 1 List.remove(0) 2 return true 3. else return false 40 / 130
  • 70. Images/cinvestav- Next Case Cont... 2. else if (List.get(0)==’[0-9]|[+-]’) 1 List.remove(0) 2 return Rec-Paren(List) Last Step 3. else if (List.get(0)==’)’) 1 List.remove(0) 2 return true 3. else return false 40 / 130
  • 71. Images/cinvestav- Next Case Cont... 2. else if (List.get(0)==’[0-9]|[+-]’) 1 List.remove(0) 2 return Rec-Paren(List) Last Step 3. else if (List.get(0)==’)’) 1 List.remove(0) 2 return true 3. else return false 40 / 130
  • 72. Images/cinvestav- Next Case Cont... 2. else if (List.get(0)==’[0-9]|[+-]’) 1 List.remove(0) 2 return Rec-Paren(List) Last Step 3. else if (List.get(0)==’)’) 1 List.remove(0) 2 return true 3. else return false 40 / 130
  • 73. Images/cinvestav- Next Case Cont... 2. else if (List.get(0)==’[0-9]|[+-]’) 1 List.remove(0) 2 return Rec-Paren(List) Last Step 3. else if (List.get(0)==’)’) 1 List.remove(0) 2 return true 3. else return false 40 / 130
  • 74. Images/cinvestav- Developing a Recursive Solution II What if you have? What if we have (a+b? What about What if we have a+b)? 41 / 130
  • 75. Images/cinvestav- Developing a Recursive Solution II What if you have? What if we have (a+b? What about What if we have a+b)? 41 / 130
  • 76. Images/cinvestav- This solution fails!!! So, we need to send something down the recursion What do we do? Ideas 42 / 130
  • 77. Images/cinvestav- What about...? what if We send down a flag!! 43 / 130
  • 78. Images/cinvestav- Thus We need a flag to send down the recursion!!! To tell the logic if we saw a left parenthesis Ok For simple problems fine!!! However... 44 / 130
  • 79. Images/cinvestav- Thus We need a flag to send down the recursion!!! To tell the logic if we saw a left parenthesis Ok For simple problems fine!!! However... 44 / 130
  • 80. Images/cinvestav- Then For problems like these ones ((a+b) Nope It does not work 45 / 130
  • 81. Images/cinvestav- Then For problems like these ones ((a+b) Nope It does not work 45 / 130
  • 82. Images/cinvestav- We need something more complex A counter!!! To see how many “(” we have seen down the recursion!!! 46 / 130
  • 83. Images/cinvestav- Recursive Solution - You assume a list of characters p u b l i c s t a t i c boolean Balanced ( C h a i n L i n e a r L i s t L i s t , i n t Counter ){ i f ( L i s t . isEmpty ( ) ) { // Check empty i f ( Counter == 0) // Check Counter r e t u r n t r u e ; e l s e r e t u r n f a l s e ;} i f ( L i s t . get (0)== ’ ( ’ ) // Case ( { Counter++; L i s t . remove ( 0 ) ; r e t u r n Balanced ( L i s t , Counter ) ; } e l s e i f ( L i s t . get (0)== ’ [0 −9]|[+ −] ’ ) // Case Number or −+ { L i s t . remove ( 0 ) ; r e t u r n Balanced ( L i s t , Counter ) ; } e l s e i f ( L i s t . get (0)== ’ ) ’ ) // Case ) { i f ( Counter > 0){ Counter −−; L i s t . remove ( 0 ) ; r e t u r n Balanced ( L i s t , Counter ) } e l s e r e t u r n f a l s e ; } e l s e r e t u r n f a l s e } 47 / 130
  • 84. Images/cinvestav- Can we simplify our code? Yes Using this memory container the STACK!!! 48 / 130
  • 85. Images/cinvestav- Before Anything Else Did you notice something about my Chain during the recursion? What? 49 / 130
  • 89. Images/cinvestav- So, we can simulate the recursion using what? First a way to... ITERATE A memory storage A Stack So somebody? Can give a process for it? 53 / 130
  • 90. Images/cinvestav- So, we can simulate the recursion using what? First a way to... ITERATE A memory storage A Stack So somebody? Can give a process for it? 53 / 130
  • 91. Images/cinvestav- So, we can simulate the recursion using what? First a way to... ITERATE A memory storage A Stack So somebody? Can give a process for it? 53 / 130
  • 92. Images/cinvestav- Iterative Solution - You assume a list of characters p u b l i c s t a t i c boolean Balanced ( C h a i n L i n e a r L i s t L i s t ){ Stack I t = new Stack ( ) ; i f ( L i s t . isEmpty ( ) ) r e t u r n t r u e w h i l e ( ! L i s t . isEmpty ( ) ) { // Use a loop i f ( L i s t . get (0)== ’ ( ’ ) { I t . push ( L i s t . get ( 0 ) ) ; L i s t . remove ( 0 ) ; } e l s e i f ( L i s t . get (0)== ’ [0 −9]|[+ −] ’ ) { L i s t . remove (0) } e l s e i f ( L i s t . get (0)== ’ ) ’ ) { i f ( ! I t . empty ( ) ) I t . pop ( ) ; e l s e r e t u r n f a l s e ; L i s t . remove ( 0 ) ; // Yes remove the // l a s t ")" } i f ( I t . empty ( ) ) r e t u r n t r u e ; r e t u r n f a l s e } 54 / 130
  • 93. Images/cinvestav- Outline 1 Introduction Example ADT 2 Examples Parentheses Matching Towers of Hanoi Chess Method Invocation And Return Method Invocation And Return Rat In A Maze 3 Implementation Derivation From ArrayLinearList Derivation From Chain 4 Code Snippets 55 / 130
  • 94. Images/cinvestav- The Puzzle The Leyend There is a story about an Indian temple in Kashi Vishwanath which contains a large room with three time-worn posts in it surrounded by 64 golden disks. Something Notable Brahmin priests, acting out the command of an ancient prophecy, have been moving these disks, in accordance with the immutable rules of the Brahma, since that time. So According to the legend, when the last move of the puzzle will be completed, the world will end. 56 / 130
  • 95. Images/cinvestav- The Puzzle The Leyend There is a story about an Indian temple in Kashi Vishwanath which contains a large room with three time-worn posts in it surrounded by 64 golden disks. Something Notable Brahmin priests, acting out the command of an ancient prophecy, have been moving these disks, in accordance with the immutable rules of the Brahma, since that time. So According to the legend, when the last move of the puzzle will be completed, the world will end. 56 / 130
  • 96. Images/cinvestav- The Puzzle The Leyend There is a story about an Indian temple in Kashi Vishwanath which contains a large room with three time-worn posts in it surrounded by 64 golden disks. Something Notable Brahmin priests, acting out the command of an ancient prophecy, have been moving these disks, in accordance with the immutable rules of the Brahma, since that time. So According to the legend, when the last move of the puzzle will be completed, the world will end. 56 / 130
  • 97. Images/cinvestav- A simple example with 3 disks The objective of the puzzle is to move the entire stack to the end rod 57 / 130
  • 98. Images/cinvestav- A simple example with 3 disks The objective of the puzzle is to move the entire stack to the end rod 58 / 130
  • 99. Images/cinvestav- A simple example with 3 disks The objective of the puzzle is to move the entire stack to the end rod 59 / 130
  • 100. Images/cinvestav- A simple example with 3 disks The objective of the puzzle is to move the entire stack to the end rod 60 / 130
  • 101. Images/cinvestav- A simple example with 3 disks The objective of the puzzle is to move the entire stack to the end rod 61 / 130
  • 102. Images/cinvestav- A simple example with 3 disks The objective of the puzzle is to move the entire stack to the end rod 62 / 130
  • 103. Images/cinvestav- A simple example with 3 disks The objective of the puzzle is to move the entire stack to the end rod 63 / 130
  • 104. Images/cinvestav- A simple example with 3 disks The objective of the puzzle is to move the entire stack to the end rod 64 / 130
  • 105. Images/cinvestav- The Rules First One Only one disk can be moved at a time. Second One Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. Third One No disk may be placed on top of a smaller disk. 65 / 130
  • 106. Images/cinvestav- The Rules First One Only one disk can be moved at a time. Second One Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. Third One No disk may be placed on top of a smaller disk. 65 / 130
  • 107. Images/cinvestav- The Rules First One Only one disk can be moved at a time. Second One Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. Third One No disk may be placed on top of a smaller disk. 65 / 130
  • 108. Images/cinvestav- Properties With Three disk You can solve it in seven moves Thus, the minimum number of moves required for n disks 2n − 1 (1) So how we solve the problem recursively? Ideas? 66 / 130
  • 109. Images/cinvestav- Properties With Three disk You can solve it in seven moves Thus, the minimum number of moves required for n disks 2n − 1 (1) So how we solve the problem recursively? Ideas? 66 / 130
  • 110. Images/cinvestav- Properties With Three disk You can solve it in seven moves Thus, the minimum number of moves required for n disks 2n − 1 (1) So how we solve the problem recursively? Ideas? 66 / 130
  • 112. Images/cinvestav- Next The other things Let n be the total number of discs. Number the discs from 1 (smallest, topmost) to n (largest, bottommost) How we solve this problem? We can use the technique of “Divide and Conquer” 68 / 130
  • 113. Images/cinvestav- Next The other things Let n be the total number of discs. Number the discs from 1 (smallest, topmost) to n (largest, bottommost) How we solve this problem? We can use the technique of “Divide and Conquer” 68 / 130
  • 114. Images/cinvestav- Next The other things Let n be the total number of discs. Number the discs from 1 (smallest, topmost) to n (largest, bottommost) How we solve this problem? We can use the technique of “Divide and Conquer” 68 / 130
  • 115. Images/cinvestav- Divide and Conquer Divide and Conquer It is an important algorithm design paradigm based on multi-branched recursion. Divide This phase of the algorithm works by recursively breaking down a problem into two or more sub-problems of the same (or related) type. The Conquer I Then these subproblems become simple enough to be solved directly. 69 / 130
  • 116. Images/cinvestav- Divide and Conquer Divide and Conquer It is an important algorithm design paradigm based on multi-branched recursion. Divide This phase of the algorithm works by recursively breaking down a problem into two or more sub-problems of the same (or related) type. The Conquer I Then these subproblems become simple enough to be solved directly. 69 / 130
  • 117. Images/cinvestav- Divide and Conquer Divide and Conquer It is an important algorithm design paradigm based on multi-branched recursion. Divide This phase of the algorithm works by recursively breaking down a problem into two or more sub-problems of the same (or related) type. The Conquer I Then these subproblems become simple enough to be solved directly. 69 / 130
  • 118. Images/cinvestav- Divide and Conquer The Conquer II The solutions to the sub-problems are then combined to give a solution to the original problem. 70 / 130
  • 119. Images/cinvestav- Question!! First What is the clever thing to do? Example 71 / 130
  • 120. Images/cinvestav- A Simple Divide Phase Move everything The things that are in front of disk n. In the previous case n = 3 Ok How the recursion looks as simple logic steps? 72 / 130
  • 121. Images/cinvestav- A Simple Divide Phase Move everything The things that are in front of disk n. In the previous case n = 3 Ok How the recursion looks as simple logic steps? 72 / 130
  • 122. Images/cinvestav- The Initial Recursion Logical Steps To move n discs from tower A to tower C: 1 Move n − 1 discs from A to B using C as a temporary!!! 2 This leaves disc n alone on tower A move disc n from A to C. 3 Move n − 1 discs from B to C so they sit on disc n using A as temporary!!! 73 / 130
  • 123. Images/cinvestav- The Initial Recursion Logical Steps To move n discs from tower A to tower C: 1 Move n − 1 discs from A to B using C as a temporary!!! 2 This leaves disc n alone on tower A move disc n from A to C. 3 Move n − 1 discs from B to C so they sit on disc n using A as temporary!!! 73 / 130
  • 124. Images/cinvestav- The Initial Recursion Logical Steps To move n discs from tower A to tower C: 1 Move n − 1 discs from A to B using C as a temporary!!! 2 This leaves disc n alone on tower A move disc n from A to C. 3 Move n − 1 discs from B to C so they sit on disc n using A as temporary!!! 73 / 130
  • 125. Images/cinvestav- The Initial Recursion Logical Steps To move n discs from tower A to tower C: 1 Move n − 1 discs from A to B using C as a temporary!!! 2 This leaves disc n alone on tower A move disc n from A to C. 3 Move n − 1 discs from B to C so they sit on disc n using A as temporary!!! 73 / 130
  • 126. Images/cinvestav- Recursive Solution Code // Assume the l i s t i n A i s i n d e c r e a s i n g order p u b l i c s t a t i c S t r i n g TH( i n t n , Char Origin , Char Destination , Char Temp){ S t r i n g r e s u l t ; i f ( n = = 1){ r e t u r n "Move␣ Disk ␣"+n+"␣from␣"+ Or ig in + "␣ to ␣" + D e s t i n a t i o n + "n" ; } r e s u l t = TH(n−1, Origin , Temp , D e s t i n a t i o n ) ; r e s u l t+= "Move␣ Disk ␣"+n+"␣from␣"+ O ri gi n + "␣ to ␣" + D e s t i n a t i o n + "n" ; r e s u l t+= TH(n−1,Temp , Destination , Or ig i n ) ; r e t u r n r e s u l t s ; } 74 / 130
  • 127. Images/cinvestav- What do we need for the iterative solution? Storage for the disks Use one stack per tower!!! A while loop to simulate the recursion Doing What? 75 / 130
  • 128. Images/cinvestav- What do we need for the iterative solution? Storage for the disks Use one stack per tower!!! A while loop to simulate the recursion Doing What? 75 / 130
  • 129. Images/cinvestav- Simple Logic to the Iterative Version Logic A simple solution for the toy puzzle: 1 Alternate moves between the smallest piece and a non-smallest piece. 2 When moving the smallest piece, always move it to the next position in the same direction. 3 If there is no tower position in the chosen direction, move the piece to the opposite end, but then continue to move in the correct direction. 76 / 130
  • 130. Images/cinvestav- Simple Logic to the Iterative Version Logic A simple solution for the toy puzzle: 1 Alternate moves between the smallest piece and a non-smallest piece. 2 When moving the smallest piece, always move it to the next position in the same direction. 3 If there is no tower position in the chosen direction, move the piece to the opposite end, but then continue to move in the correct direction. 76 / 130
  • 131. Images/cinvestav- Simple Logic to the Iterative Version Logic A simple solution for the toy puzzle: 1 Alternate moves between the smallest piece and a non-smallest piece. 2 When moving the smallest piece, always move it to the next position in the same direction. 3 If there is no tower position in the chosen direction, move the piece to the opposite end, but then continue to move in the correct direction. 76 / 130
  • 132. Images/cinvestav- Simple Logic to the Iterative Version Logic A simple solution for the toy puzzle: 1 Alternate moves between the smallest piece and a non-smallest piece. 2 When moving the smallest piece, always move it to the next position in the same direction. 3 If there is no tower position in the chosen direction, move the piece to the opposite end, but then continue to move in the correct direction. 76 / 130
  • 133. Images/cinvestav- A simple example with 3 disks The objective of the puzzle is to move the entire stack to the end rod 77 / 130
  • 134. Images/cinvestav- We have two cases When there are n disks n is even When there are n disk n is odd Then a really simple solution involving 2n−1 − 1 moves You have three stacks: A, B, C. 78 / 130
  • 135. Images/cinvestav- We have two cases When there are n disks n is even When there are n disk n is odd Then a really simple solution involving 2n−1 − 1 moves You have three stacks: A, B, C. 78 / 130
  • 136. Images/cinvestav- We have two cases When there are n disks n is even When there are n disk n is odd Then a really simple solution involving 2n−1 − 1 moves You have three stacks: A, B, C. 78 / 130
  • 137. Images/cinvestav- We have for n even Use Circular moves A =⇒ B =⇒ C =⇒ A (2) 79 / 130
  • 138. Images/cinvestav- We have for n odd Use Circular Moves A =⇒ C =⇒ B =⇒ A (3) 80 / 130
  • 139. Images/cinvestav- Process IterativeHT using three stacks : towerA, towerB, towerC 1 for i = 1 to 2n−1 1 If (n%2 == 0) 1 Select the smallest disk at the top of the stacks 2 Move the smallest disk one position in the direction of the cyclic order for even order. 3 Move the next largest disk to the only possible stack 2 else 1 Select the smallest disk at the top of the stacks 2 Move the smallest disk one position in the direction of the cyclic order for odd order. 3 Move the next largest disk to the only possible stack 81 / 130
  • 140. Images/cinvestav- Process IterativeHT using three stacks : towerA, towerB, towerC 1 for i = 1 to 2n−1 1 If (n%2 == 0) 1 Select the smallest disk at the top of the stacks 2 Move the smallest disk one position in the direction of the cyclic order for even order. 3 Move the next largest disk to the only possible stack 2 else 1 Select the smallest disk at the top of the stacks 2 Move the smallest disk one position in the direction of the cyclic order for odd order. 3 Move the next largest disk to the only possible stack 81 / 130
  • 141. Images/cinvestav- Process IterativeHT using three stacks : towerA, towerB, towerC 1 for i = 1 to 2n−1 1 If (n%2 == 0) 1 Select the smallest disk at the top of the stacks 2 Move the smallest disk one position in the direction of the cyclic order for even order. 3 Move the next largest disk to the only possible stack 2 else 1 Select the smallest disk at the top of the stacks 2 Move the smallest disk one position in the direction of the cyclic order for odd order. 3 Move the next largest disk to the only possible stack 81 / 130
  • 142. Images/cinvestav- Process IterativeHT using three stacks : towerA, towerB, towerC 1 for i = 1 to 2n−1 1 If (n%2 == 0) 1 Select the smallest disk at the top of the stacks 2 Move the smallest disk one position in the direction of the cyclic order for even order. 3 Move the next largest disk to the only possible stack 2 else 1 Select the smallest disk at the top of the stacks 2 Move the smallest disk one position in the direction of the cyclic order for odd order. 3 Move the next largest disk to the only possible stack 81 / 130
  • 143. Images/cinvestav- Process IterativeHT using three stacks : towerA, towerB, towerC 1 for i = 1 to 2n−1 1 If (n%2 == 0) 1 Select the smallest disk at the top of the stacks 2 Move the smallest disk one position in the direction of the cyclic order for even order. 3 Move the next largest disk to the only possible stack 2 else 1 Select the smallest disk at the top of the stacks 2 Move the smallest disk one position in the direction of the cyclic order for odd order. 3 Move the next largest disk to the only possible stack 81 / 130
  • 144. Images/cinvestav- Process IterativeHT using three stacks : towerA, towerB, towerC 1 for i = 1 to 2n−1 1 If (n%2 == 0) 1 Select the smallest disk at the top of the stacks 2 Move the smallest disk one position in the direction of the cyclic order for even order. 3 Move the next largest disk to the only possible stack 2 else 1 Select the smallest disk at the top of the stacks 2 Move the smallest disk one position in the direction of the cyclic order for odd order. 3 Move the next largest disk to the only possible stack 81 / 130
  • 145. Images/cinvestav- Process IterativeHT using three stacks : towerA, towerB, towerC 1 for i = 1 to 2n−1 1 If (n%2 == 0) 1 Select the smallest disk at the top of the stacks 2 Move the smallest disk one position in the direction of the cyclic order for even order. 3 Move the next largest disk to the only possible stack 2 else 1 Select the smallest disk at the top of the stacks 2 Move the smallest disk one position in the direction of the cyclic order for odd order. 3 Move the next largest disk to the only possible stack 81 / 130
  • 146. Images/cinvestav- Process IterativeHT using three stacks : towerA, towerB, towerC 1 for i = 1 to 2n−1 1 If (n%2 == 0) 1 Select the smallest disk at the top of the stacks 2 Move the smallest disk one position in the direction of the cyclic order for even order. 3 Move the next largest disk to the only possible stack 2 else 1 Select the smallest disk at the top of the stacks 2 Move the smallest disk one position in the direction of the cyclic order for odd order. 3 Move the next largest disk to the only possible stack 81 / 130
  • 147. Images/cinvestav- Process IterativeHT using three stacks : towerA, towerB, towerC 1 for i = 1 to 2n−1 1 If (n%2 == 0) 1 Select the smallest disk at the top of the stacks 2 Move the smallest disk one position in the direction of the cyclic order for even order. 3 Move the next largest disk to the only possible stack 2 else 1 Select the smallest disk at the top of the stacks 2 Move the smallest disk one position in the direction of the cyclic order for odd order. 3 Move the next largest disk to the only possible stack 81 / 130
  • 148. Images/cinvestav- What about the Most Efficient Version? You need a node state 1 Number of Disks 2 Origin Tower 3 Destination Tower 4 Temporary Tower 82 / 130
  • 149. Images/cinvestav- What about the Most Efficient Version? You need a node state 1 Number of Disks 2 Origin Tower 3 Destination Tower 4 Temporary Tower 82 / 130
  • 150. Images/cinvestav- What about the Most Efficient Version? You need a node state 1 Number of Disks 2 Origin Tower 3 Destination Tower 4 Temporary Tower 82 / 130
  • 151. Images/cinvestav- What about the Most Efficient Version? You need a node state 1 Number of Disks 2 Origin Tower 3 Destination Tower 4 Temporary Tower 82 / 130
  • 152. Images/cinvestav- We have then the following logic procedure Iterative-Hanoi(n) 1 let S be an stack 2 let Result be a empty string 3 S.push(Node(n, A, C, B, Result)) 4 while S is not empty 5 v = S.pop() 6 if (v.n == 1) 7 print "Move one from v.Origin to v.Destination n" 8 else 9 S.push(Node(v.n-1, v.Temp, v.Destination, v.Origin)) 10 S.push(Node(1, v.Origin, v.Destination, v.Temp)) 11 S.push(Node(v.n-1,v.Origin, v.Temp, v.Destination)) 83 / 130
  • 153. Images/cinvestav- We have then the following logic procedure Iterative-Hanoi(n) 1 let S be an stack 2 let Result be a empty string 3 S.push(Node(n, A, C, B, Result)) 4 while S is not empty 5 v = S.pop() 6 if (v.n == 1) 7 print "Move one from v.Origin to v.Destination n" 8 else 9 S.push(Node(v.n-1, v.Temp, v.Destination, v.Origin)) 10 S.push(Node(1, v.Origin, v.Destination, v.Temp)) 11 S.push(Node(v.n-1,v.Origin, v.Temp, v.Destination)) 83 / 130
  • 154. Images/cinvestav- We have then the following logic procedure Iterative-Hanoi(n) 1 let S be an stack 2 let Result be a empty string 3 S.push(Node(n, A, C, B, Result)) 4 while S is not empty 5 v = S.pop() 6 if (v.n == 1) 7 print "Move one from v.Origin to v.Destination n" 8 else 9 S.push(Node(v.n-1, v.Temp, v.Destination, v.Origin)) 10 S.push(Node(1, v.Origin, v.Destination, v.Temp)) 11 S.push(Node(v.n-1,v.Origin, v.Temp, v.Destination)) 83 / 130
  • 155. Images/cinvestav- We have then the following logic procedure Iterative-Hanoi(n) 1 let S be an stack 2 let Result be a empty string 3 S.push(Node(n, A, C, B, Result)) 4 while S is not empty 5 v = S.pop() 6 if (v.n == 1) 7 print "Move one from v.Origin to v.Destination n" 8 else 9 S.push(Node(v.n-1, v.Temp, v.Destination, v.Origin)) 10 S.push(Node(1, v.Origin, v.Destination, v.Temp)) 11 S.push(Node(v.n-1,v.Origin, v.Temp, v.Destination)) 83 / 130
  • 156. Images/cinvestav- We have then the following logic procedure Iterative-Hanoi(n) 1 let S be an stack 2 let Result be a empty string 3 S.push(Node(n, A, C, B, Result)) 4 while S is not empty 5 v = S.pop() 6 if (v.n == 1) 7 print "Move one from v.Origin to v.Destination n" 8 else 9 S.push(Node(v.n-1, v.Temp, v.Destination, v.Origin)) 10 S.push(Node(1, v.Origin, v.Destination, v.Temp)) 11 S.push(Node(v.n-1,v.Origin, v.Temp, v.Destination)) 83 / 130
  • 157. Images/cinvestav- We have then the following logic procedure Iterative-Hanoi(n) 1 let S be an stack 2 let Result be a empty string 3 S.push(Node(n, A, C, B, Result)) 4 while S is not empty 5 v = S.pop() 6 if (v.n == 1) 7 print "Move one from v.Origin to v.Destination n" 8 else 9 S.push(Node(v.n-1, v.Temp, v.Destination, v.Origin)) 10 S.push(Node(1, v.Origin, v.Destination, v.Temp)) 11 S.push(Node(v.n-1,v.Origin, v.Temp, v.Destination)) 83 / 130
  • 158. Images/cinvestav- We have then the following logic procedure Iterative-Hanoi(n) 1 let S be an stack 2 let Result be a empty string 3 S.push(Node(n, A, C, B, Result)) 4 while S is not empty 5 v = S.pop() 6 if (v.n == 1) 7 print "Move one from v.Origin to v.Destination n" 8 else 9 S.push(Node(v.n-1, v.Temp, v.Destination, v.Origin)) 10 S.push(Node(1, v.Origin, v.Destination, v.Temp)) 11 S.push(Node(v.n-1,v.Origin, v.Temp, v.Destination)) 83 / 130
  • 159. Images/cinvestav- We have then the following logic procedure Iterative-Hanoi(n) 1 let S be an stack 2 let Result be a empty string 3 S.push(Node(n, A, C, B, Result)) 4 while S is not empty 5 v = S.pop() 6 if (v.n == 1) 7 print "Move one from v.Origin to v.Destination n" 8 else 9 S.push(Node(v.n-1, v.Temp, v.Destination, v.Origin)) 10 S.push(Node(1, v.Origin, v.Destination, v.Temp)) 11 S.push(Node(v.n-1,v.Origin, v.Temp, v.Destination)) 83 / 130
  • 160. Images/cinvestav- We have then the following logic procedure Iterative-Hanoi(n) 1 let S be an stack 2 let Result be a empty string 3 S.push(Node(n, A, C, B, Result)) 4 while S is not empty 5 v = S.pop() 6 if (v.n == 1) 7 print "Move one from v.Origin to v.Destination n" 8 else 9 S.push(Node(v.n-1, v.Temp, v.Destination, v.Origin)) 10 S.push(Node(1, v.Origin, v.Destination, v.Temp)) 11 S.push(Node(v.n-1,v.Origin, v.Temp, v.Destination)) 83 / 130
  • 161. Images/cinvestav- We have then the following logic procedure Iterative-Hanoi(n) 1 let S be an stack 2 let Result be a empty string 3 S.push(Node(n, A, C, B, Result)) 4 while S is not empty 5 v = S.pop() 6 if (v.n == 1) 7 print "Move one from v.Origin to v.Destination n" 8 else 9 S.push(Node(v.n-1, v.Temp, v.Destination, v.Origin)) 10 S.push(Node(1, v.Origin, v.Destination, v.Temp)) 11 S.push(Node(v.n-1,v.Origin, v.Temp, v.Destination)) 83 / 130
  • 162. Images/cinvestav- What about the Legend? To solve the towers of Hanoi for 64 disks We need ≈ 1.8 ∗ 1019 moves With a computer making 109 moves/second A computer would take about 570 years to complete. At 1 disk move/min The monks will take about 3.4 × 1013 years. The sun will destroy the life on earth in 2.8 × 109. 84 / 130
  • 163. Images/cinvestav- What about the Legend? To solve the towers of Hanoi for 64 disks We need ≈ 1.8 ∗ 1019 moves With a computer making 109 moves/second A computer would take about 570 years to complete. At 1 disk move/min The monks will take about 3.4 × 1013 years. The sun will destroy the life on earth in 2.8 × 109. 84 / 130
  • 164. Images/cinvestav- What about the Legend? To solve the towers of Hanoi for 64 disks We need ≈ 1.8 ∗ 1019 moves With a computer making 109 moves/second A computer would take about 570 years to complete. At 1 disk move/min The monks will take about 3.4 × 1013 years. The sun will destroy the life on earth in 2.8 × 109. 84 / 130
  • 165. Images/cinvestav- Outline 1 Introduction Example ADT 2 Examples Parentheses Matching Towers of Hanoi Chess Method Invocation And Return Method Invocation And Return Rat In A Maze 3 Implementation Derivation From ArrayLinearList Derivation From Chain 4 Code Snippets 85 / 130
  • 166. Images/cinvestav- Chess As in the Tower of Hanoi It is possible to devise a massive search solution based in the actual state of the chess board. State 0 86 / 130
  • 167. Images/cinvestav- Chess As in the Tower of Hanoi It is possible to devise a massive search solution based in the actual state of the chess board. State 0 86 / 130
  • 168. Images/cinvestav- Then Something Notable If you put 1 penny for the first square, 2 for next, 4 for next, 8 for next, and so on. You have $3.6 ∗ 1017 (federal budget ~ 2 ∗ 1012) . 87 / 130
  • 169. Images/cinvestav- Then Something Notable If you put 1 penny for the first square, 2 for next, 4 for next, 8 for next, and so on. You have $3.6 ∗ 1017 (federal budget ~ 2 ∗ 1012) . 87 / 130
  • 170. Images/cinvestav- Outline 1 Introduction Example ADT 2 Examples Parentheses Matching Towers of Hanoi Chess Method Invocation And Return Method Invocation And Return Rat In A Maze 3 Implementation Derivation From ArrayLinearList Derivation From Chain 4 Code Snippets 88 / 130
  • 171. Images/cinvestav- Method Invocation And Return We have stack in the memory system 89 / 130
  • 172. Images/cinvestav- Method Invocation And Return We have stack in the memory system 90 / 130
  • 173. Images/cinvestav- Method Invocation And Return We have stack in the memory system 91 / 130
  • 174. Images/cinvestav- Outline 1 Introduction Example ADT 2 Examples Parentheses Matching Towers of Hanoi Chess Method Invocation And Return Method Invocation And Return Rat In A Maze 3 Implementation Derivation From ArrayLinearList Derivation From Chain 4 Code Snippets 92 / 130
  • 175. Images/cinvestav- Try-Throw-Catch Thus 1 When you enter a try block, push the address of this block on a stack. 2 When an exception is thrown, pop the try block that is at the top of the stack (if the stack is empty, terminate). 3 If the popped try block has no matching catch block, go back to the preceding step. 4 If the popped try block has a matching catch block, execute the matching catch block. 93 / 130
  • 176. Images/cinvestav- Try-Throw-Catch Thus 1 When you enter a try block, push the address of this block on a stack. 2 When an exception is thrown, pop the try block that is at the top of the stack (if the stack is empty, terminate). 3 If the popped try block has no matching catch block, go back to the preceding step. 4 If the popped try block has a matching catch block, execute the matching catch block. 93 / 130
  • 177. Images/cinvestav- Try-Throw-Catch Thus 1 When you enter a try block, push the address of this block on a stack. 2 When an exception is thrown, pop the try block that is at the top of the stack (if the stack is empty, terminate). 3 If the popped try block has no matching catch block, go back to the preceding step. 4 If the popped try block has a matching catch block, execute the matching catch block. 93 / 130
  • 178. Images/cinvestav- Try-Throw-Catch Thus 1 When you enter a try block, push the address of this block on a stack. 2 When an exception is thrown, pop the try block that is at the top of the stack (if the stack is empty, terminate). 3 If the popped try block has no matching catch block, go back to the preceding step. 4 If the popped try block has a matching catch block, execute the matching catch block. 93 / 130
  • 179. Images/cinvestav- Outline 1 Introduction Example ADT 2 Examples Parentheses Matching Towers of Hanoi Chess Method Invocation And Return Method Invocation And Return Rat In A Maze 3 Implementation Derivation From ArrayLinearList Derivation From Chain 4 Code Snippets 94 / 130
  • 180. Images/cinvestav- Rat In A Maze Example 95 / 130
  • 181. Images/cinvestav- Rat In A Maze Example Move order is: right, down, left, up Block positions to avoid revisit. 96 / 130
  • 182. Images/cinvestav- Rat In A Maze Example 97 / 130
  • 183. Images/cinvestav- Rat In A Maze Example Move backward until we reach a square from which a forward move is possible. 98 / 130
  • 184. Images/cinvestav- Rat In A Maze Example Move backward until we reach a square from which a forward move is possible. 99 / 130
  • 185. Images/cinvestav- Rat In A Maze Example MOVE DOWN 100 / 130
  • 186. Images/cinvestav- Rat In A Maze Example MOVE LEFT 101 / 130
  • 187. Images/cinvestav- Rat In A Maze Example MOVE DOWN 102 / 130
  • 188. Images/cinvestav- Rat In A Maze Example Move backward until we reach a square from which a forward move is possible. 103 / 130
  • 189. Images/cinvestav- Outline 1 Introduction Example ADT 2 Examples Parentheses Matching Towers of Hanoi Chess Method Invocation And Return Method Invocation And Return Rat In A Maze 3 Implementation Derivation From ArrayLinearList Derivation From Chain 4 Code Snippets 104 / 130
  • 190. Images/cinvestav- Derivation From ArrayLinearList We can do the following Stack top is either left end or right end of linear list For any possible top empty() =⇒ isEmpty() O(1) time peek() =⇒ get(0) or get(size() - 1) O(1) time 105 / 130
  • 191. Images/cinvestav- Derivation From ArrayLinearList We can do the following Stack top is either left end or right end of linear list For any possible top empty() =⇒ isEmpty() O(1) time peek() =⇒ get(0) or get(size() - 1) O(1) time 105 / 130
  • 192. Images/cinvestav- Derivation From ArrayLinearList We can do the following Stack top is either left end or right end of linear list For any possible top empty() =⇒ isEmpty() O(1) time peek() =⇒ get(0) or get(size() - 1) O(1) time 105 / 130
  • 193. Images/cinvestav- Derivation From ArrayLinearList We can do the following Stack top is either left end or right end of linear list For any possible top empty() =⇒ isEmpty() O(1) time peek() =⇒ get(0) or get(size() - 1) O(1) time 105 / 130
  • 194. Images/cinvestav- Derivation From ArrayLinearList We can do the following Stack top is either left end or right end of linear list For any possible top empty() =⇒ isEmpty() O(1) time peek() =⇒ get(0) or get(size() - 1) O(1) time 105 / 130
  • 195. Images/cinvestav- Derivation From ArrayLinearList When top is left end of linear list push(theObject) =⇒ add(0, theObject) O(size) time pop() =⇒ remove(0) O(size) time 106 / 130
  • 196. Images/cinvestav- Derivation From ArrayLinearList When top is left end of linear list push(theObject) =⇒ add(0, theObject) O(size) time pop() =⇒ remove(0) O(size) time 106 / 130
  • 197. Images/cinvestav- Derivation From ArrayLinearList When top is left end of linear list push(theObject) =⇒ add(0, theObject) O(size) time pop() =⇒ remove(0) O(size) time 106 / 130
  • 198. Images/cinvestav- Derivation From ArrayLinearList When top is left end of linear list push(theObject) =⇒ add(0, theObject) O(size) time pop() =⇒ remove(0) O(size) time 106 / 130
  • 199. Images/cinvestav- Derivation From ArrayLinearList When top is right end of linear list For any possible top push(theObject) =⇒ add(size(), theObject) O(1) time pop() =⇒ remove(size()-1) O(1) time 107 / 130
  • 200. Images/cinvestav- Derivation From ArrayLinearList When top is right end of linear list For any possible top push(theObject) =⇒ add(size(), theObject) O(1) time pop() =⇒ remove(size()-1) O(1) time 107 / 130
  • 201. Images/cinvestav- Derivation From ArrayLinearList When top is right end of linear list For any possible top push(theObject) =⇒ add(size(), theObject) O(1) time pop() =⇒ remove(size()-1) O(1) time 107 / 130
  • 202. Images/cinvestav- Derivation From ArrayLinearList When top is right end of linear list For any possible top push(theObject) =⇒ add(size(), theObject) O(1) time pop() =⇒ remove(size()-1) O(1) time 107 / 130
  • 203. Images/cinvestav- Derivation From ArrayLinearList When top is right end of linear list For any possible top push(theObject) =⇒ add(size(), theObject) O(1) time pop() =⇒ remove(size()-1) O(1) time 107 / 130
  • 204. Images/cinvestav- Thus The Moral of the Story You must use the right end of list as top of stack That is way 108 / 130
  • 205. Images/cinvestav- Thus The Moral of the Story You must use the right end of list as top of stack That is way STACK DATA TEXT HEAP 0 High Memory Growing Directions 108 / 130
  • 206. Images/cinvestav- Outline 1 Introduction Example ADT 2 Examples Parentheses Matching Towers of Hanoi Chess Method Invocation And Return Method Invocation And Return Rat In A Maze 3 Implementation Derivation From ArrayLinearList Derivation From Chain 4 Code Snippets 109 / 130
  • 207. Images/cinvestav- Derivation from a Chain Stack top is either left end or right end of linear list CA EDB firstNode NULL Thus empty() =⇒ isEmpty() O(1) time 110 / 130
  • 208. Images/cinvestav- Derivation from a Chain Stack top is either left end or right end of linear list CA EDB firstNode NULL Thus empty() =⇒ isEmpty() O(1) time 110 / 130
  • 209. Images/cinvestav- Derivation from a Chain Stack top is either left end or right end of linear list CA EDB firstNode NULL Thus empty() =⇒ isEmpty() O(1) time 110 / 130
  • 210. Images/cinvestav- Derivation from a Chain When top is left end of linear list CA EDB firstNode NULL Thus peek() =⇒ get(0) O(1) time push(theObject) =⇒ add(0, theObject) O(1) time pop() =⇒ remove(0) O(1) time 111 / 130
  • 211. Images/cinvestav- Derivation from a Chain When top is left end of linear list CA EDB firstNode NULL Thus peek() =⇒ get(0) O(1) time push(theObject) =⇒ add(0, theObject) O(1) time pop() =⇒ remove(0) O(1) time 111 / 130
  • 212. Images/cinvestav- Derivation from a Chain When top is left end of linear list CA EDB firstNode NULL Thus peek() =⇒ get(0) O(1) time push(theObject) =⇒ add(0, theObject) O(1) time pop() =⇒ remove(0) O(1) time 111 / 130
  • 213. Images/cinvestav- Derivation from a Chain When top is left end of linear list CA EDB firstNode NULL Thus peek() =⇒ get(0) O(1) time push(theObject) =⇒ add(0, theObject) O(1) time pop() =⇒ remove(0) O(1) time 111 / 130
  • 214. Images/cinvestav- Derivation from a Chain When top is left end of linear list CA EDB firstNode NULL Thus peek() =⇒ get(0) O(1) time push(theObject) =⇒ add(0, theObject) O(1) time pop() =⇒ remove(0) O(1) time 111 / 130
  • 215. Images/cinvestav- Derivation from a Chain When top is left end of linear list CA EDB firstNode NULL Thus peek() =⇒ get(0) O(1) time push(theObject) =⇒ add(0, theObject) O(1) time pop() =⇒ remove(0) O(1) time 111 / 130
  • 216. Images/cinvestav- Derivation from a Chain When top is left end of linear list CA EDB firstNode NULL Thus peek() =⇒ get(0) O(1) time push(theObject) =⇒ add(0, theObject) O(1) time pop() =⇒ remove(0) O(1) time 111 / 130
  • 217. Images/cinvestav- Derivation from a Chain When top is left end of linear list CA EDB firstNode NULL Thus peek() =⇒ get(size()-1) O(size) time push(theObject) =⇒ add(size(), theObject) O(size) time pop() =⇒ remove(size()-1) O(size) time 112 / 130
  • 218. Images/cinvestav- Derivation from a Chain When top is left end of linear list CA EDB firstNode NULL Thus peek() =⇒ get(size()-1) O(size) time push(theObject) =⇒ add(size(), theObject) O(size) time pop() =⇒ remove(size()-1) O(size) time 112 / 130
  • 219. Images/cinvestav- Derivation from a Chain When top is left end of linear list CA EDB firstNode NULL Thus peek() =⇒ get(size()-1) O(size) time push(theObject) =⇒ add(size(), theObject) O(size) time pop() =⇒ remove(size()-1) O(size) time 112 / 130
  • 220. Images/cinvestav- Derivation from a Chain When top is left end of linear list CA EDB firstNode NULL Thus peek() =⇒ get(size()-1) O(size) time push(theObject) =⇒ add(size(), theObject) O(size) time pop() =⇒ remove(size()-1) O(size) time 112 / 130
  • 221. Images/cinvestav- Derivation from a Chain When top is left end of linear list CA EDB firstNode NULL Thus peek() =⇒ get(size()-1) O(size) time push(theObject) =⇒ add(size(), theObject) O(size) time pop() =⇒ remove(size()-1) O(size) time 112 / 130
  • 222. Images/cinvestav- Derivation from a Chain When top is left end of linear list CA EDB firstNode NULL Thus peek() =⇒ get(size()-1) O(size) time push(theObject) =⇒ add(size(), theObject) O(size) time pop() =⇒ remove(size()-1) O(size) time 112 / 130
  • 223. Images/cinvestav- Derivation from a Chain When top is left end of linear list CA EDB firstNode NULL Thus peek() =⇒ get(size()-1) O(size) time push(theObject) =⇒ add(size(), theObject) O(size) time pop() =⇒ remove(size()-1) O(size) time 112 / 130
  • 224. Images/cinvestav- Thus The Moral of the Story You must use the left end of list as top of stack 113 / 130
  • 225. Images/cinvestav- Derive From ArrayLinearList Code package MyStack ; import java . u t i l . ∗ ; // I t has stack e x c e p t i o n p u b l i c c l a s s DerivedArrayStack extends A r r a y L i n e a r L i s t <Item> { // c o n s t r u c t o r s come here // Stack i n t e r f a c e methods come here } 114 / 130
  • 226. Images/cinvestav- Derive From ArrayLinearList Constructors /∗∗ c r e a t e a stack with the given i n i t i a l ∗ c a p a c i t y ∗/ p u b l i c DerivedArrayStack ( i n t i n i t i a l C a p a c i t y ) { super ( i n i t i a l C a p a c i t y ) ; } /∗∗ c r e a t e a stack with i n i t i a l c a p a c i t y 10 ∗/ p u b l i c DerivedArrayStack () { t h i s ( 1 0 ) ; } 115 / 130
  • 227. Images/cinvestav- empty() And peek() Code p u b l i c boolean empty () { r e t u r n isEmpty ( ) ; } p u b l i c Object peek () { i f ( empty ( ) ) throw new EmptyStackException ( ) ; r e t u r n get ( s i z e () − 1 ) ; } 116 / 130
  • 228. Images/cinvestav- push(theObject) And pop() Code p u b l i c void push ( Object theElement ) {add ( s i z e ( ) , theElement ) ; } p u b l i c Object pop () { i f ( empty ( ) ) throw new EmptyStackException ( ) ; r e t u r n remove ( s i z e () − 1 ) ; } 117 / 130
  • 229. Images/cinvestav- The Pros The merits of deriving from ArrayLinearList Code for derived class is quite simple and easy to develop. Code is expected to require little debugging. Code for other stack implementations such as a linked implementation are easily obtained. Just replace extends ArrayLinearList with extends Chain. For efficiency reasons we must also make changes to use the left end of the list as the stack top rather than the right end. 118 / 130
  • 230. Images/cinvestav- The Pros The merits of deriving from ArrayLinearList Code for derived class is quite simple and easy to develop. Code is expected to require little debugging. Code for other stack implementations such as a linked implementation are easily obtained. Just replace extends ArrayLinearList with extends Chain. For efficiency reasons we must also make changes to use the left end of the list as the stack top rather than the right end. 118 / 130
  • 231. Images/cinvestav- The Pros The merits of deriving from ArrayLinearList Code for derived class is quite simple and easy to develop. Code is expected to require little debugging. Code for other stack implementations such as a linked implementation are easily obtained. Just replace extends ArrayLinearList with extends Chain. For efficiency reasons we must also make changes to use the left end of the list as the stack top rather than the right end. 118 / 130
  • 232. Images/cinvestav- The Pros The merits of deriving from ArrayLinearList Code for derived class is quite simple and easy to develop. Code is expected to require little debugging. Code for other stack implementations such as a linked implementation are easily obtained. Just replace extends ArrayLinearList with extends Chain. For efficiency reasons we must also make changes to use the left end of the list as the stack top rather than the right end. 118 / 130
  • 233. Images/cinvestav- The Pros The merits of deriving from ArrayLinearList Code for derived class is quite simple and easy to develop. Code is expected to require little debugging. Code for other stack implementations such as a linked implementation are easily obtained. Just replace extends ArrayLinearList with extends Chain. For efficiency reasons we must also make changes to use the left end of the list as the stack top rather than the right end. 118 / 130
  • 234. Images/cinvestav- The Cons Then All public methods of ArrayLinearList are performed following the stack structure: get(0) . . . get bottom element remove(5)... pop add(3, x) ... push So we do not have a true stack implementation. We must override undesired methods. 119 / 130
  • 235. Images/cinvestav- The Cons Then All public methods of ArrayLinearList are performed following the stack structure: get(0) . . . get bottom element remove(5)... pop add(3, x) ... push So we do not have a true stack implementation. We must override undesired methods. 119 / 130
  • 236. Images/cinvestav- The Cons Then All public methods of ArrayLinearList are performed following the stack structure: get(0) . . . get bottom element remove(5)... pop add(3, x) ... push So we do not have a true stack implementation. We must override undesired methods. 119 / 130
  • 237. Images/cinvestav- The Cons Then All public methods of ArrayLinearList are performed following the stack structure: get(0) . . . get bottom element remove(5)... pop add(3, x) ... push So we do not have a true stack implementation. We must override undesired methods. 119 / 130
  • 238. Images/cinvestav- The Cons Then All public methods of ArrayLinearList are performed following the stack structure: get(0) . . . get bottom element remove(5)... pop add(3, x) ... push So we do not have a true stack implementation. We must override undesired methods. 119 / 130
  • 239. Images/cinvestav- The Cons Unnecessary work is done by the code. Examples Example I peek() verifies that the stack is not empty before get is invoked. The index check done by get is, therefore, not needed. Example II add(size(), theElement) does an index check and a for loop that is not entered. Neither is needed. 120 / 130
  • 240. Images/cinvestav- The Cons Unnecessary work is done by the code. Examples Example I peek() verifies that the stack is not empty before get is invoked. The index check done by get is, therefore, not needed. Example II add(size(), theElement) does an index check and a for loop that is not entered. Neither is needed. 120 / 130
  • 241. Images/cinvestav- The Cons Unnecessary work is done by the code. Examples Example I peek() verifies that the stack is not empty before get is invoked. The index check done by get is, therefore, not needed. Example II add(size(), theElement) does an index check and a for loop that is not entered. Neither is needed. 120 / 130
  • 242. Images/cinvestav- The Cons Unnecessary work is done by the code. Examples Example I peek() verifies that the stack is not empty before get is invoked. The index check done by get is, therefore, not needed. Example II add(size(), theElement) does an index check and a for loop that is not entered. Neither is needed. 120 / 130
  • 243. Images/cinvestav- The Cons Unnecessary work is done by the code. Examples Example I peek() verifies that the stack is not empty before get is invoked. The index check done by get is, therefore, not needed. Example II add(size(), theElement) does an index check and a for loop that is not entered. Neither is needed. 120 / 130
  • 244. Images/cinvestav- Then Thus So the derived code runs slower than necessary. 121 / 130
  • 245. Images/cinvestav- Moral of the Story First Code developed from scratch will run faster but will take more time (cost) to develop. Second Tradeoff between software development cost and performance. Third Tradeoff between time to market and performance. Fourth It could be easy to develop the code first and later refine it to improve performance. 122 / 130
  • 246. Images/cinvestav- Moral of the Story First Code developed from scratch will run faster but will take more time (cost) to develop. Second Tradeoff between software development cost and performance. Third Tradeoff between time to market and performance. Fourth It could be easy to develop the code first and later refine it to improve performance. 122 / 130
  • 247. Images/cinvestav- Moral of the Story First Code developed from scratch will run faster but will take more time (cost) to develop. Second Tradeoff between software development cost and performance. Third Tradeoff between time to market and performance. Fourth It could be easy to develop the code first and later refine it to improve performance. 122 / 130
  • 248. Images/cinvestav- Moral of the Story First Code developed from scratch will run faster but will take more time (cost) to develop. Second Tradeoff between software development cost and performance. Third Tradeoff between time to market and performance. Fourth It could be easy to develop the code first and later refine it to improve performance. 122 / 130
  • 249. Images/cinvestav- Example A slow pop 1 if (empty()) 2 throw new EmptyStackException(); 3 return remove(size() - 1); Faster Code 1 try {return remove(size() - 1);} 2 catch(IndexOutOfBoundsException e) 3 {throw new EmptyStackException();} 123 / 130
  • 250. Images/cinvestav- Example A slow pop 1 if (empty()) 2 throw new EmptyStackException(); 3 return remove(size() - 1); Faster Code 1 try {return remove(size() - 1);} 2 catch(IndexOutOfBoundsException e) 3 {throw new EmptyStackException();} 123 / 130
  • 251. Images/cinvestav- Example A slow pop 1 if (empty()) 2 throw new EmptyStackException(); 3 return remove(size() - 1); Faster Code 1 try {return remove(size() - 1);} 2 catch(IndexOutOfBoundsException e) 3 {throw new EmptyStackException();} 123 / 130
  • 252. Images/cinvestav- Example A slow pop 1 if (empty()) 2 throw new EmptyStackException(); 3 return remove(size() - 1); Faster Code 1 try {return remove(size() - 1);} 2 catch(IndexOutOfBoundsException e) 3 {throw new EmptyStackException();} 123 / 130
  • 253. Images/cinvestav- Example A slow pop 1 if (empty()) 2 throw new EmptyStackException(); 3 return remove(size() - 1); Faster Code 1 try {return remove(size() - 1);} 2 catch(IndexOutOfBoundsException e) 3 {throw new EmptyStackException();} 123 / 130
  • 254. Images/cinvestav- Example A slow pop 1 if (empty()) 2 throw new EmptyStackException(); 3 return remove(size() - 1); Faster Code 1 try {return remove(size() - 1);} 2 catch(IndexOutOfBoundsException e) 3 {throw new EmptyStackException();} 123 / 130
  • 255. Images/cinvestav- Code From Scratch First Use a 1D array stack whose data type is Item. same as using array element in ArrayLinearList Second Use an int variable top. Stack elements are in stack[0:top]. Top element is in stack[top]. Bottom element is in stack[0]. Stack is empty iff top = -1. Number of elements in stack is top+1. 124 / 130
  • 256. Images/cinvestav- Code From Scratch First Use a 1D array stack whose data type is Item. same as using array element in ArrayLinearList Second Use an int variable top. Stack elements are in stack[0:top]. Top element is in stack[top]. Bottom element is in stack[0]. Stack is empty iff top = -1. Number of elements in stack is top+1. 124 / 130
  • 257. Images/cinvestav- Code From Scratch First Use a 1D array stack whose data type is Item. same as using array element in ArrayLinearList Second Use an int variable top. Stack elements are in stack[0:top]. Top element is in stack[top]. Bottom element is in stack[0]. Stack is empty iff top = -1. Number of elements in stack is top+1. 124 / 130
  • 258. Images/cinvestav- Code From Scratch First Use a 1D array stack whose data type is Item. same as using array element in ArrayLinearList Second Use an int variable top. Stack elements are in stack[0:top]. Top element is in stack[top]. Bottom element is in stack[0]. Stack is empty iff top = -1. Number of elements in stack is top+1. 124 / 130
  • 259. Images/cinvestav- Code From Scratch First Use a 1D array stack whose data type is Item. same as using array element in ArrayLinearList Second Use an int variable top. Stack elements are in stack[0:top]. Top element is in stack[top]. Bottom element is in stack[0]. Stack is empty iff top = -1. Number of elements in stack is top+1. 124 / 130
  • 260. Images/cinvestav- Code From Scratch First Use a 1D array stack whose data type is Item. same as using array element in ArrayLinearList Second Use an int variable top. Stack elements are in stack[0:top]. Top element is in stack[top]. Bottom element is in stack[0]. Stack is empty iff top = -1. Number of elements in stack is top+1. 124 / 130
  • 261. Images/cinvestav- Code From Scratch First Use a 1D array stack whose data type is Item. same as using array element in ArrayLinearList Second Use an int variable top. Stack elements are in stack[0:top]. Top element is in stack[top]. Bottom element is in stack[0]. Stack is empty iff top = -1. Number of elements in stack is top+1. 124 / 130
  • 262. Images/cinvestav- Code From Scratch First Use a 1D array stack whose data type is Item. same as using array element in ArrayLinearList Second Use an int variable top. Stack elements are in stack[0:top]. Top element is in stack[top]. Bottom element is in stack[0]. Stack is empty iff top = -1. Number of elements in stack is top+1. 124 / 130
  • 263. Images/cinvestav- Code From Scratch Data Memember package Stack ; import java . u t i l . EmptyStackException ; import u t i l i t i e s . ∗ ; p u b l i c c l a s s ArrayStack<Item> implements Stack<Item> { // data members i n t top ; // c u r r e n t top of stack Item [ ] stack ; // element a r r a y // Etc } 125 / 130
  • 264. Images/cinvestav- Constructors Code p u b l i c ArrayStack ( i n t i n i t i a l C a p a c i t y ) { i f ( i n i t i a l C a p a c i t y < 1) throw new I l l e g a l A r g u m e n t E x c e p t i o n ( " i n i t i a l C a p a c i t y ␣must␣be␣>=␣1" ) ; t h i s . stack = ( Item [ ] ) new Object [ i n i t i a l C a p a c i t y ] ; top = −1; } p u b l i c ArrayStack () { t h i s ( 1 0 ) ; } 126 / 130
  • 265. Images/cinvestav- Push(...) Code p u b l i c void push ( Object theElement ) { // i n c r e a s e a r r a y s i z e i f n e c e s s a r y i f ( top == stack . le ngth − 1) stack = ChangeArrayLength . changeLength1D ( stack , 2 ∗ stack . l ength ) ; // put theElement at the top of the stack stack[++top ] = theElement ; } Thus 127 / 130
  • 266. Images/cinvestav- Pop() Code p u b l i c Item pop () { i f ( empty ( ) ) throw new EmptyStackException ( ) ; Object topElement = stack [ top ] ; stack [ top −−] = n u l l ; // enable garbage c o l l e c t i o n r e t u r n topElement ; } Thus 128 / 130
  • 267. Images/cinvestav- Actually We have the following java.util.Stack It derives from java.util.Vector. java.util.Vector is an array implementation of a linear list. 129 / 130
  • 268. Images/cinvestav- Performance of 500,000 pop, push, and peek operations We have Class 500,000 DerivedArrayStack 0.38 s Scratch Array Stack 0.22 s DerivedArrayStackWithCatch 0.33 s DerivedLinkedStack 3.20 s Scratch LinkedStack 2.96 s 130 / 130