Stacks (Application, ADT Interface, Implementation) Outline and Required Reading: (§ 4.1) • Stacks • Sample Case Study (§ 4.5)
COSC 2011, Fall 2003, Section A Instructor: N. Vlajic
2
Stack ADT Stack – linear data structure organized according to “last-in/first-out” (LIFO) principle ! stack items can be inserted and removed only at one end ! stack items are taken out of the stack in reverse order of their insertion ! in a stack, only top element is accessible!
C B A
Examples – page visited history in a Web browser, undo sequence in a text editor, etc.
3
Stack ADT: Application (1) Java Virtual Machine
–
(Java Method Invocation)
keeps track of the chain of currently active methods by using a stack • at the top of the stack is the frame of the currently running method, i.e. method that has control over the execution
• the remaining elements of the stack are suspended methods that have invoked another method and are waiting for its termination
invoked method
Top of Java Stack: currently running method
terminated method
job2: … job1: … main: … Java Stack
main() { … job1(); }; job1() { … job2(); };
4
Stack ADT: Application (1) (cont.) Java VM and Recursion
–
! fact(1) is called last, but it must (will) be executed first - all other method calls are awaiting for its execution
fact(1)
! fact(1) is executed without invoking itself recursively !!!