Stack. Examine the item most recently added LIFO: last in first out
Queue. Examine the item least recently added FIFI: first in first out
Stack pop:
Stack push:
Using
array to implement Stack
Use array s[] to store N items on stack.
push(): add new item at s[N]
.
pop(): remove item from s[N-1].
(Note: We don’t add the exception in the push and pop operation above)
Underflow: throw exception if pop from an empty stack
Overflow: use resizing array for array implementation
About the "pop operation” that we use “Loitering” (not release when it is no longer needed)above. So for the space efficient, we do modification like:
How to avoid confirm “capacity” previously? Resizing array implementation
First try.
Push(): increase size of array s[] by 1.
It is too expensive, time proportional is 1 + 2 + … + N ~ N^2/2
So how?
Answer: if array is full, create a new array of twice the
size, and copy items
Pop():halve size of array s[] when array is one-quarter full
so the array is between 25% and 100% full
Queue
Array Queue of implementing resizing
use array q[] to store items in queue.
enqueue(): add new item at q[tail]; dequeue(): remove item from q[head]
Update head and tail modulo the capacity
So far we have implemented: StackOfStrings. What if we also want: StackOfURLs, StackOfInts, StackOfVans… (multiple types)
We use Java generics.
1. It doesn’t need client to cast object.
2. Discover type mismatch errors at compile-time rather than run-time
(welcome compile-time errors; avoid run-time errors)
we implement "generic stack" in linked-list stack compared with “StackOfStrings" implementation.
However, "generic stack” cannot be implemented in array stack.
So we modify line 7 into this: In this method, we need to cast Object by client. We see that this is not a good code because it needs casting.
what is an Iterable?
what is an Iterator?
Why we need data structures Iterable?
linked-list implementation of Stack iterator
Array implementation of Stack iterator
The linked list iterator will work without modification because the items in the linked list are ordered in FIFO order (which is the main reason we dequeue from the front and enqueue to the back instead of vice versa). The array iterator will fail for two reasons: (i) the items should be iterated over in the opposite order and (ii) the items won't typically be stored in the array as entries 0 to N-1
Dijkstra’s two stack algorithm
Value: push onto the value stack
Operator: push
month the operator stack
“(“: ignore
“)”: pop operator and two values; push the result of applying that operator to those values onto the operand stack