Lists, stacks and queues
Introducido
7:45
Estructuras de datos y algoritmos
This course is about choosing a container by what it costs. The first unit is the yardstick: how cost grows with the size of the input. The next four are the…
Narración en inglés · subtítulos en inglés y 中文 que puedes cambiar
En esta lección
| English | Significado |
|---|---|
| array/əˈreɪ/ | arreglo |
| linked list/lɪŋkt lɪst/ | lista enlazada |
| node/nəʊd/ | nodo |
| stack/stæk/ | pila |
| queue/kjuː/ | cola |
| amortised/əˈmɔːtaɪzd/ | averaged over a long sequence of operations, so rare expensive steps are shared out among many cheap ones |
| LRU cache/ˌel ɑː ˈjuː kæʃ/ | A cache that evicts the least recently used item when full, usually built from a hash map and a doubly linked list. |
Dos diseños, extremos distintos
- Una lista de Python es un array contiguo: el índice $i$ calcula la dirección en un paso, pero insertar al principio desliza a todos. Una lista enlazada intercambia el salto por empalmes baratos: cada nodo lleva un puntero al siguiente.
- Una pila añade y elimina en un extremo (LIFO); una cola entra por un extremo y sale por el otro (FIFO).


Index number i in a contiguous array costs —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
The cells sit side by side: the address is computed, not searched for.
Esta tarjeta se corrigió, por eso aparece en inglés hasta que se actualice su traducción.
Why append is amortised O(1)
- In a dynamic array that doubles when full, the total number of elements copied over $n$ appends is $O(n)$, so the average append cost is constant: amortised 均摊 $O(1)$.
- Front insertion never averages out. Every
insert(0)moves all the elements, so $n$ front inserts move $\Theta(n^2)$ elements, and the count goes up four times when $n$ doubles.
Append at the end of a Python list is —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Proportional growth gives a linear total number of copies over many appends, so the amortized cost is constant.
Rastros
- Pila: empila
push 3, push 7, push 1, luegopop, popdevuelve $1$ y después $7$ — último en entrar, primero en salir. Los corchetes equilibrados siguen la misma disciplina: escanea([]){}apilando aperturas; cada cierre debe coincidir con el tope, mientras que([)]falla porque)encuentra[en el tope. - Cola: encola
a, b, c; dos desenques devuelvenaluegob; el frente esc.collections.dequesirve ambos extremos en $O(1)$ — un bucle sobrelist.pop(0)es la trampa clásica de $O(n)$.
Dos pilas simulan una cola: una bandeja de entrada y una de salida, cada elemento se maneja como máximo dos veces — por eso una deque real hace ambos extremos de forma nativa.
Last in, first out
Step through push 3, push 7, push 1, then two pops. The pops return 1 then 7, and 3 stays at the bottom.
push 3, push 7, push 1, pop, pop returns —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
A stack pops in reverse push order: last in, first out.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Counting the copies
- Start a dynamic array at capacity $1$ and double it when full. Sixteen appends cause regrows at the $2$nd, $3$rd, $5$th and $9$th append, which copy $1 + 2 + 4 + 8 = 15$ elements, fewer than $n$. Writes plus copies stay under $2n$, so each append costs $O(1)$ amortised 均摊.
- Grow by a fixed $+10$ instead and the copies add up to about $n^2/20$: quadratic again. The growth factor matters, not the size of the step. Choose a structure by the end that is busy: undo needs a stack, a print queue needs a queue, a sliding window needs a deque.
Capacity starts at 1 and doubles when full. How many element copies do 32 appends cause?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
Regrows copy 1 + 2 + 4 + 8 + 16 = 31 elements, still under n.
An editor must undo the most recent change first. The right structure is —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
The last change made is the first undone: last in, first out.
Growing a dynamic array by a fixed $10$ extra slots each time it fills still makes append amortised $O(1)$.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
A fixed step regrows every $10$ appends and each regrow copies everything, so the copies total about $n^2/20$: quadratic. Only a constant growth factor, such as doubling, makes append amortised $O(1)$.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Two structures, one cache
- A doubly linked list moves or removes a node in $O(1)$ once you hold it; a hash map finds a node in $O(1)$. Together they make an LRU cache LRU缓存 (least recently used): every get moves the item to the front, and a full cache removes the item at the tail.
- Neither structure can do it alone: the list cannot find a key, and the map has no order. Python's
OrderedDictwithmove_to_endis exactly this pair.
A hash map alone gives an LRU cache with O(1) eviction.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
It has no order to find the least recently used item; the linked list supplies it.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Worked example: a ring-buffer queue
- Store a queue 队列 in an array of capacity 8, with
headandtailindices taken mod 8. From an empty queue athead = tail = 6, enqueue three items: they go into slots 6, 7 and 0. - Now
tail$= (6 + 3) \bmod 8 = \mathbf{1}$, and the size is $(1 - 6) \bmod 8 = 3$. Both ends stay $O(1)$ with no shifting.dequeblocks and network buffers work this way.
Ring buffer of capacity 8, empty with head = tail = 6; enqueue 3 items. New tail index?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
$(6 + 3) \bmod 8 = 1$.
Capacity 8, head 6, tail 1: number of items?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
$(1 - 6) \bmod 8 = 3$.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Marks that slip away
list.pop(0)in a loop. Each call moves every element, so emptying $n$ items costs $\Theta(n^2)$. Usecollections.deque.- Calling every append $O(1)$. A regrow copies everything; only the average over many appends is constant.
- Mixing up the ends. Push 3, 7, 1: a stack 栈 gives back 1 first, a queue gives back 3.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Recap
| Operation | Array | Linked list 链表 |
|---|---|---|
| Index lookup | $O(1)$ | $O(n)$ |
| Insert at the front | $O(n)$ | $O(1)$ |
| Append at the end | $O(1)$ amortised | $O(1)$ with a tail pointer |
| Splice in a held node | $O(n)$ | $O(1)$ |
- Doubling makes append amortised $O(1)$: $15$ copies for $16$ appends.
- Stack is LIFO, queue is FIFO;
collections.dequeserves both ends in $O(1)$.
¿Qué salió mal? Solo el equipo del sitio ve esta información.