Let’s take a moment and talk about two new abstract data types: Stacks and Queues.
A stack is a data structure that is LIFO (Last-In-First-Out). You can picture it as a stack of items where you put new items on the top and also, remove items from the top.
Here is a simple interface that could be used to describe a stack:
public interface Stack<DataType> {
// Return true if the stack is empty, false otherwise
public boolean isEmpty();
// Put a new item on top of the stack
public void push(DataType value);
// Remove the top item from the top of the stack and return it
public DataType pop();
// Return the top item from the stack, but don't remove it from the stack
public DataType peek();
}
Here are some real-world examples of stack usage:
Stacks of plates at a buffet. (New plates are put on top and plates are also removed from the top.)
“Undo” operations in programs. (You undo the last change made.)
RPN calculators.
A queue is a data structure that is FIFO (First-In-First-Out). You can picture it as a tube. You put items into one end, but you remove them from the other end.
Here is a simple interface that could be used to describe a queue:
public interface Queue<DataType> {
// Return true if the queue is empty
public boolean isEmpty();
// Put a new item onto the end of the queue
public void enqueue(DataType value);
// Remove an item from the head the queue and return it
public DataType dequeue();
// Return the item from the head of the queue, but don't remove it from the queue
public DataType peek();
}
Here are some real-world examples of queue usage:
The check-out line at the grocery store.
The list of students on the whiteboard during a busy office hours session.
The way food should be stored and used in your refrigerator.
If you implement a stack with an ArrayList
, can all the operations be \(O(1)\)? Why or why not?
If you implement a stack with a LinkedList
, can all the operations be \(O(1)\)? Why or why not?
If you implement a queue with an ArrayList
, can all the operations be \(O(1)\)? Why or why not?
If you implement a queue with a LinkedList
, can all the operations be \(O(1)\)? Why or why not?