Junior — Middle
What is the difference between a stack data structure and a queue?
sobes.tech AI
Answer from AI
A stack and a queue are data structures for storing elements with different access rules.
-
Stack operates on the LIFO (Last In, First Out) principle — the last added element is retrieved first. Imagine a stack of plates: you take the top one.
-
Queue operates on the FIFO (First In, First Out) principle — the first added element is retrieved first. It's similar to a line in a store: the first to arrive is the first to be served.
In Python, a stack can be implemented using a list with the append() and pop() methods. A queue is more conveniently implemented using collections.deque.
Example of a stack:
stack = []
stack.append(1) # add
stack.append(2)
print(stack.pop()) # retrieve 2
Example of a queue:
from collections import deque
queue = deque()
queue.append(1) # add
queue.append(2)
print(queue.popleft()) # retrieve 1