Notes / Data Structures & Algorithms
Queue and stack: first come and last come
A work queue is a queue; function calls are a stack. Implement both directly with arrays and see the difference.
Queue: first in, first out (FIFO)
Data where order matters (button events, packets waiting to be sent, a list of commands) is stacked in a queue. A ring buffer is exactly a fixed-size queue. An RTOS message queue is the same idea with locking and waiting added.
Stack: last in, first out (LIFO)
static int16_t st[16];
static uint8_t top;
void push(int16_t v) { if (top < 16) st[top++] = v; }
int16_t pop(void) { return top ? st[--top] : 0; }
The CPU, too, pushes the return address and local variables on a stack when it calls a function, because the function called last finishes first. A stack is also the natural fit for implementing "back" in a menu screen.
Which to use when
| Situation | Structure |
|---|---|
| Process in arrival order | Queue |
| Going back, nested structures | Stack |
| Most urgent first | Priority queue |
In embedded work both are built as fixed-size arrays, and what happens on overflow (drop, overwrite, flag an error) is decided from the start.