1 Chapter 5 Stacks
2 Topics LIFO (last-in-first-out) structure Implementations –Use class LinearList or Chain –from scratch Applications –parentheses matching –tower of Hanoi –Re-arranging Railroad cars –computer-aided design of circuit field –offline equivalence class –rat in a maze
3 Stacks
4 Abstract data type
5 Formula-based representation
6 Formula-based representation (continue)
7 Efficiency of Stack Constructor and destructor –Θ(1) when T is an internal data type –Θ(MaxStackSize) when T is user-defined all other operations - Θ(1)
8 Customized definition of Stack
9 Customized definition of Stack (continue)
10 Customized definition of Stack (continue)
11 Two stacks in an array Multiple stacks in an array –Worst-case add time - O(ArraySize) –delete time - Θ
12 Linked Stack
13 Linked Stack (continue)
14 Customized linked stack each operation takes Θ(1) time
15 Customized linked stack (continue)
16 Customized linked stack (continue)
17 Customized linked stack (continue)
18 Customized linked stack (continue)
19 Parenthesis matching - Θ(n)
20 Parenthesis matching (continue)
21 Parenthesis matching (continue)
22 Sample run
23 Towers of Hanoi
24 Recursive function
25 Time complexity moves(n) = –0 when n = 0 –2moves(n-1)+1 when n > 0 moves(n) = 2 n - 1 Θ(2 n )
26 Towers of Hanoi using stacks
27 Towers of Hanoi using stacks (continue)
28 Towers of Hanoi using stacks (continue)
29 Rearranging railroad cars
30 Rules A car may be moved from the front of the input track to the top of one of the holding tracks or to the left end of the output track A car may be moved from the top of a holding track to the left end of the output track whenever the car labels in a holding track are not in increasing order from top to bottom, the rearrangement cannot be completed new car u is moved to the holding track that has at its top a car with smallest label v such that v > u
31 Track states
32 Railroad car rearrangement program - O(kn)
33 Railroad car rearrangement program (continue)
34 Railroad car rearrangement program (continue)
35 Output - Θ(k)
36 Output (continue)
37 Hold - Θ(k)
38 Hold (continue)
39 Hold (continue)
40 Switch box routing
41 The routing program - Θ(n)
42 The routing program (continue)
43 Rat in a Maze
44 Matrix Rep
45 The end of Chapter 5