A stack is like a stack of plates: you can only add or remove plates from the top. The last plate you put on is the first one you take off — Last In, First Out (LIFO).
class Stack:
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
if not self.is_empty():
return self._items.pop()
return None
def peek(self):
if not self.is_empty():
return self._items[-1]
return None
def is_empty(self):
return len(self._items) == 0
A queue is like a line at a supermarket: the first person in line is served first. First In, First Out (FIFO).
In a linear queue, we use a fixed-size array with two pointers: front (pointing to the first element) and rear (pointing to the next empty slot).
items[rear] = x; rear++ — add at the rearx = items[front]; items[front] = null; front++ — remove from the frontA circular queue solves the wasted-space problem by wrapping around: when rear reaches the end, it goes back to index 0 if there's space. We leave one slot empty to distinguish "full" from "empty".
items[rear] = x; rear = (rear + 1) % sizex = items[front]; items[front] = null; front = (front + 1) % sizefront == rear(rear + 1) % size == frontfrom collections import deque
class Queue:
def __init__(self):
self._items = deque()
def enqueue(self, item):
self._items.append(item)
def dequeue(self):
return self._items.popleft()
def front(self):
return self._items[0]
def is_empty(self):
return len(self._items) == 0
collections.deque (double-ended queue) because removing from the front of a list is O(n), but deque.popleft() is O(1).