Lec5 Stack Queue
Lec5 Stack Queue
Method ArrayList
add O(1)
add(index, value) O(N)
indexOf O(N)
get O(1)
remove O(N)
set O(1)
size O(1)
front back
top 3 remove, peek add
1 2 3
2
queue
bottom 1
stack
Abstract data types (ADTs)
• abstract data type (ADT): A specification of a collection of
data and the operations that can be performed on it.
– Describes what a collection does, not how it does it
• Sophisticated algorithms:
– searching through a maze with "backtracking"
– many programs use an "undo stack" of previous operations
Class Stack
Stack<E>() constructs a new stack with elements of type E
push(value) places given value on top of stack
pop() removes top value from stack and returns it;
throws EmptyStackException if stack is empty
peek() returns top value from stack without removing it;
throws EmptyStackException if stack is empty
size() returns number of elements in stack
isEmpty() returns true if stack has no elements
grades.add(3.2);
grades.add(2.7);
...
double myGrade = grades.get(0);
Stack limitations/idioms
• You cannot loop over a stack in the usual way.
Stack<Integer> s = new Stack<Integer>();
...
for (int i = 0; i < s.size(); i++) {
do something with s.get(i);
}
front back
remove, peek add
• basic queue operations: 1 2 3
– add (enqueue): Add an element to the back.
queue
– remove (dequeue): Remove the front element.
– peek: Examine the front element.
Queues in computer science
• Operating systems:
– queue of print jobs to send to the printer
– queue of programs / processes to be run
– queue of network data packets to send
• Programming:
– modeling a line of customers or clients
– storing a queue of computations to be performed in order