Two simple rules for adding and removing items, and a surprising amount of real software depends on picking the right one. A stack always deals with the most recent addition first. A queue always deals with the oldest one first. That's the entire idea, everything else follows from it.
Push adds to the top. Pop removes from the top. Whatever went in most recently is the first thing to come back out, like a stack of plates: you take from the top, not the bottom.
Here's a stack doing genuine arithmetic. Postfix notation (also called Reverse Polish Notation) writes operators after their operands: "3 4 +" means 3 + 4. Read left to right: push every number you see, and whenever you hit an operator, pop the two most recent numbers, apply it, and push the result back.
Nobody writes "3 4 +" by hand, you write "3 + 4" and a computer converts it. This is that conversion, called the shunting-yard algorithm, and it uses a stack too, a completely different one from the evaluation stack above. Try the same three expressions and watch them turn into exactly the postfix you already evaluated.
Enqueue adds to the back. Dequeue removes from the front. Whatever's been waiting longest is served first, exactly like a real queue at a shop.
| Added in this order | Stack removes in | Queue removes in |
|---|---|---|
| A, B, C | C, B, A | A, B, C |
Feed the same three values into both structures above and check this table matches what you see. The data is identical, only the order of removal differs, and that difference is the whole reason both structures exist.
The queue above works, but if it's built on a fixed-size array, removing from the front normally means shifting every remaining item along, which is slow. A circular queue fixes this: front and rear pointers just wrap back to index 0 once they reach the end, so freed slots at the front get reused without shifting anything. Watch the pointers actually move around the ring below.
A fixed 8-slot buffer. Watch the rear pointer wrap from index 7 back to 0, then to 1, reusing a slot freed earlier.
pointer = (pointer + 1) mod size, which is exactly what makes them wrap back to 0.Bare brackets on their own don't mean much, so here's the algorithm doing its actual job: checking a calculation is well-formed before anything tries to evaluate it. This is exactly what a calculator or code editor runs before working out the answer to something like (3 + (4 * 2)) - (5 - 1).