Files
G4G0-2/Data Structures/GPT Answers to Past Paper/Question 2.md
2025-03-16 18:59:42 +00:00

42 lines
2.4 KiB
Markdown
Executable File

# Describe a Scenario where a Stack Data Structure Would Be More Suitable than a Queue
A **stack data structure** is more suitable than a queue in scenarios where you need to process items in a **Last-In, First-Out (LIFO)** order
### Scenario: **Undo Operation in Text Editors**
- **Description**: In text editors, when a user types, deletes, or performs other actions, these operations are stored so they can be undone in reverse order of execution.
- **Why a Stack?**:
- The most recent action (the "last-in") is the first one that should be undone (the "first-out").
- A stack efficiently tracks these operations, allowing actions to be added to the stack as they occur and popped off when the user undoes them.
- **How It Works**:
1. User types "Hello" → each character is pushed onto the stack.
2. User presses "Undo" → the stack pops the last character added.
### Scenario: **Call Stack in Recursion**
- **Description**: When a program uses recursion, the function calls are nested, and each call must finish before the previous one can resume.
- **Why a Stack?**:
- The current function (most recent call) must finish execution (be "popped" off the stack) before the previous function call can resume.
- The stack keeps track of the state and local variables for each function call.
- **How It Works**:
1. Function `A` calls `B`, which calls `C`.
2. The stack stores the execution state of `A`, then `B`, then `C` (last-in).
3. When `C` finishes, its state is removed (first-out), resuming `B`.
### Scenario: **Browser Backtracking**
- **Description**: When navigating a web browser, the "Back" button relies on a stack to revisit the most recently visited page.
- **Why a Stack?**:
- The most recent page (last-in) should be revisited first (first-out) when the user clicks "Back".
- **How It Works**:
1. User navigates to pages: A → B → C. Each page is pushed onto the stack.
2. Clicking "Back" pops the stack, returning to page `B`, then `A`.
### Key Contrast with a Queue:
- A **queue** is more suitable when processing items in a **First-In, First-Out (FIFO)** order, such as serving customer requests or scheduling tasks.
- A stack is better when you need **reversal** or to **process the most recent element first**, such as undo operations, recursion, or browser backtracking.
Describe a scenario where a stack data structure would be more suitable than a
Queue