AmbifulWorksheets
Cheat sheet
CBSE · Class 12 · Computer Science

Queue

A queue is FIFO: enqueue at the rear and dequeue from the front of a Python list; a deque works at both ends. Underflow, and choosing a stack, queue or deque.

Key ideas

Remember

Enqueue and dequeueq = []
q.append(5)
q.append(8)
print(q.pop(0)) # 5
print(q) # [8]
Reaching the frontthe k-th item enqueued is at the front after k − 1 dequeues
Deque endsfront: insert(0, x) and pop(0); rear: append(x) and pop()
Which structureticket line, print jobs, CPU tasks: queue; undo, back button, brackets: stack; both ends: deque

Watch out

Worked example

What does this print?
d = [47, 46]
d.insert(0, 95)
d.insert(0, 91)
d.insert(0, 99)
d.pop()
d.append(87)
print(d)

Working: append() adds at the rear, insert(0, x) at the front; pop() removes from the rear, pop(0) from the front

Answer: [99, 91, 95, 47, 87]