Sobes.tech
Middle

What is the difference between a stack, queue, and deque?

sobes.tech AI

Answer from AI

Stack, queue, and deque are data structures with different rules for adding and removing elements:

  • Stack — operates on the LIFO (Last In, First Out) principle. The last added element is removed 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 removed first. Like a line in a store: the first person in line is served first.

  • Deque (double-ended queue) — a bidirectional queue, where elements can be added and removed from both ends. It’s a hybrid of a stack and a queue.

In Python, these structures are often implemented using the collections module:

from collections import deque

stack = []  # stack
stack.append(1)
stack.append(2)
print(stack.pop())  # 2

queue = deque()  # queue
queue.append(1)
queue.append(2)
print(queue.popleft())  # 1

deque_obj = deque()
deque_obj.append(1)      # add to the right
deque_obj.appendleft(2) # add to the left
print(deque_obj.pop())      # remove from the right
print(deque_obj.popleft())  # remove from the left

Thus, the choice of structure depends on the requirements for the order of element processing.