leetExpert
Linear structures · Arrays, Linked Lists, Stacks, Queues · overview

Four ways to keep things in a line, and the systems that run on each.

Arrays, linked lists, stacks and queues all hold items in order. What sets them apart is which end you may touch and what one step costs. Eight systems, two for each structure, show the difference in software you use every day.

structures 4systems 8every frame run, not drawn

Arrays: one block, found by arithmetic

An array is one unbroken run of memory. Item i sits exactly i items past the start, so reaching it is a multiplication, whatever i is. The price is paid when the block fills up: nothing can be squeezed in, so growing means moving.

Linked lists: nodes that point onward

A linked list gives up the single block. Each node lives wherever there was room and holds a reference to the next. Finding the k-th item means walking k steps, but inserting or removing next to a node you already hold is a few pointer writes.

Stacks: the last in is the first out

A stack lets you touch one end only. What went on last comes off first, which is exactly the shape of anything nested: a function waiting on the one it called, an opening bracket waiting for its close.

Queues: the first in is the first out

A queue adds at one end and removes at the other, so items leave in the order they arrived. It is the shape of anything that is served in turn: packets off a wire, requests against a limit.

Recognise the shape

Four questions point at the right structure before any code is written.