You have a list of tasks that must be processed in the exact order they arrive. Which data structure is best to use?
Think about which data structure follows the 'first come, first served' rule.
A queue processes elements in the order they arrive (FIFO), which is perfect for task scheduling where order matters. A stack processes elements in reverse order (LIFO), which is not suitable here.
What is the printed output after executing the following Java code?
import java.util.Stack; public class Main { public static void main(String[] args) { Stack<Integer> stack = new Stack<>(); stack.push(10); stack.push(20); stack.push(30); System.out.print(stack.pop() + " -> "); System.out.print(stack.pop() + " -> "); System.out.print(stack.pop() + " -> null"); } }
Remember that stack is Last In First Out (LIFO).
The last pushed element (30) is popped first, then 20, then 10. So the output is 30 -> 20 -> 10 -> null.
What is the printed output after executing the following Java code?
import java.util.LinkedList; import java.util.Queue; public class Main { public static void main(String[] args) { Queue<Integer> queue = new LinkedList<>(); queue.add(5); queue.add(15); queue.add(25); System.out.print(queue.poll() + " -> "); System.out.print(queue.poll() + " -> "); System.out.print(queue.poll() + " -> null"); } }
Remember that queue is First In First Out (FIFO).
The first added element (5) is removed first, then 15, then 25. So the output is 5 -> 15 -> 25 -> null.
Which scenario is best suited for using a stack instead of a queue?
Think about a feature where the most recent action is reversed first.
Undo functionality requires reversing the most recent action first, which fits the Last In First Out (LIFO) behavior of a stack.
You are designing a browser history feature that allows users to go back to the previous page. Which data structure is most appropriate and why?
Think about how the 'back' button works in a browser.
The browser history 'back' button returns to the most recently visited page first, which matches the Last In First Out (LIFO) behavior of a stack.
