Intern
What is the difference between the data structures 'stack' and 'queue'?
sobes.tech AI
Answer from AI
Stack — a data structure that operates on the LIFO (Last-In, First-Out) principle. The last added element will be the first to be retrieved.
Queue — a data structure that operates on the FIFO (First-In, First-Out) principle. The first added element will be the first to be retrieved.
Main operations and their implementation:
| Operation | Stack | Queue |
|---|---|---|
| Add | push (to the end) |
enqueue (to the end) |
| Remove | pop (from the end) |
dequeue (from the front) |
| View | peek (last) |
peek (first) |
| Empty? | is_empty |
is_empty |
| Size | size |
size |
Examples of usage:
- Stack: Browser history (back button), function call management (call stack), syntax analysis.
- Queue: Task scheduler in the operating system, buffers in networks, processing requests in order.
Implementation in Python:
# Stack: can use a list
stack = []
stack.append(1) # push
stack.append(2)
item = stack.pop() # pop
# Queue: recommended to use collections.deque
from collections import deque
queue = deque()
queue.append(1) # enqueue
queue.append(2)
item = queue.popleft() # dequeue