Stacks follow a Last-In-First-Out (LIFO) order, similar to a stack of blocks where you can only add or remove from the top. The most recently added item is always the first one you can remove.
Key operations include:
push(element)
- Adds an element to the top of the stackpop()
- Removes and returns the top elementpeek()
- Returns but does not remove the top elementisEmpty()
- Checks if the stack is emptyReal-world uses of stacks include:
Stack<String> history = new Stack<>();
history.push("edit document");
history.push("delete paragraph");
history.push("add image");
// Undo last action
String lastAction = history.pop(); // returns "add image"
Queues follow a First-In-First-Out (FIFO) order, similar to people waiting in line. The first item added to the queue will be the first one removed.
Key operations include:
add(element)
or offer(element)
- Adds an element to the end of the queueremove()
or poll()
- Removes and returns the front elementelement()
or peek()
- Returns but does not remove the front elementisEmpty()
- Checks if the queue is emptyReal-world uses of queues include:
Queue<PrintJob> printQueue = new LinkedList<>();
printQueue.add(new PrintJob("document1.pdf"));
printQueue.add(new PrintJob("photo.jpg"));
printQueue.add(new PrintJob("report.docx"));
// Process next job
PrintJob nextJob = printQueue.remove(); // returns document1.pdf job
Understanding the performance characteristics of stacks and queues is essential for efficient application design:
push()
- O(1) time complexitypop()
- O(1) time complexitypeek()
- O(1) time complexityadd()/offer()
- O(1) time complexityremove()/poll()
- O(1) time complexitypeek()/element()
- O(1) time complexityThese constant-time operations make stacks and queues highly efficient for their specific use cases.
Starter code for stacks and queues implementation.
Solution code for stacks and queues implementation.
Additional examples of stacks and queues in practice.
Additional code-along exercises for this sprint.
Access the sprint challenge for this unit.