Section 7 Chapter 39 - Stacks Flashcards
Stack
A data structure that functions as an ordered collection of elements where elements can be added and removed in a “Last In, First out” way
Applications of stacks (2)
- Going back on a web browser
- Undoing
How to implement a stack
A list can be used to mimic a stack, with elements only being able to be either appended to the end, or removed from the end.
Alternatively a static array can be used with a pointer for the top of the stack
Operations on a stack (5)
- push
- pop
- peek
- isEmpty
- isFull
Overflow of a stack
A stack will have a maximum size. An attempt to add an element to a stack that would push the size past the limit will result in a stack overflow
Underflow of a stack
Will occur if the stack is attempted to be popped while being empty
Role of a stack in subroutine calls
A call stack is used when a program is running to keep track of addresses and instructions. When a subroutine is entered, its local variables, parameters and the return address are all added to the call stack (together these values form a stack frame). When the subroutine ends the stack frame is popped and the program jumps to the return address. If there are nested subroutines then the call stack may contain many stack frames
Stack frame
A call stack is composed of stack frames. Each stack frame corresponds to a call to a subroutine which has not yet terminated.
How parameters and local variables are stored
They are both stored in the stack frame
Advantage of storing local variables in the stack
It is much faster than using the heap
Contents of a stack frame
- Local variables
- Parameters
- Return address