Queue & Stack
Contents
Theory
Integer
–> null
(Zero False Null principle)
Queue
First In First Out: Breadth-First Search related problems.
Java api:
- enqueue:
offer()
- offer at the tail. - dequeue:
poll()
- poll at the head. peek()
- look at the head without polling it out.
Stack
Last In First Out
Java api:
- push:
offerFirst()
- pop:
pollFirst()
- top:
peekFirst()
Characteristics
- Move all elements from
stack1
tostack2
, the order in thestack2
is reversed. - Move all elements from
stack1
tostack2
and then move back tostack1
, the amortized time complexity for every element which is moved isO(1)
.
Amortized time vs Average time
- Average case running time: The expected behavior when the input is randomly drawn from a given distribution. The average case running time of an algorithm is an estimate of the running time for an “average” input. Often it is assumed that all inputs of a given size are equally likely.
- Amortized running time: Here the tiem required to perform a sequence of operations is averaged over all the operations performed. Amortized analysis can be used to show that the average cost of an operation is small, if one averages over a sequences of operations, even though a simple operation a expensive. Amortized analysis guarantees the average performance of each operation in the worst case.
- Worst case running time: The behavior of the algorithm with respect to the worst possible case of the input instance. The worst case running time of an algorithm is an upper bound on th erunning time for any input. Knowing it gives us a guarantee that the algorithm will never take any longer.
When we need to linearly scan a
string
/array
and continuously look back the newest element in the left, we can usestack
.
Data Structure | In Memory | Java Class | Java Interface |
---|---|---|---|
queue (FIFO) | array/linked list | ArrayDeuqe/ArrayList | Queue |
stack (LIFO) | array/linked list | ArrayDeuqe/ArrayList | Deque |
deque | array/linked list | ArrayDeuqe/ArrayList | Deque |
Algorithm Problems
Using linked list
to implement a Stack
|
|
Using linked list
to implement a Queue
|
|
Using Array
to implement a Stack
|
|
Using Array
to implement a Queue
|
|