Escolar Documentos
Profissional Documentos
Cultura Documentos
Stacks
Definition A stack is a container of objects that are inserted and removed according to the last-in-first-out principle. pushing popping Operations:
Pushing Popping
Examples
back in a web browser undo in Text editors
DSA CMT502 43
DSA CMT502
44
2 2 2 1
DSA CMT502
46
2 2 2 1
47
pop
O(1)
DSA CMT502
48
Cons
May waste memory if the actually used space is smaller than the ultimate size of the stack. May crash the applications which need a large size of stack. Difficult to delete or insert an element.
DSA CMT502 49
DSA CMT502
50
PC
UNIX
LINUX
Typical Case
DSA CMT502
Its element is called frame which is a descriptor of one of active invocations of methods.
DSA CMT502 52
func2: pc=320 m=7 func1: pc=216 j=5 k=7 main: pc=14 i=5
running method
204
216
suspended methods
Java Program
DSA CMT502
53
3.4.2 Recursion
Allows a method to call itself as a subroutine.
Example: Compute the factorial function n!=n(n-1)(n-2)..*2*1
Public static long factorial(long n){ if(n<=1) return 1; else{ int m=factorial(n-1); return n*m; } }
DSA CMT502 54
3.4.2 Recursion
main(){ int i=10; .. 12 factorial(i); .. } 215 Public static long factorial(long n) { if(n<=1) return 1; else { 221 int m=factorial(n-1); return n*m; } } factorial: pc=215 n=1
factorial: pc=221 n=2
Java Program
DSA CMT502
56
8 7
15
4 6 15
2 15
30
5 30
DSA CMT502
57