Абстрактные типы данных — стек, очередь, связный список
| English | Русский |
|---|---|
| queue/kjuː/ | queue |
| push/pʊʃ/ | толкающий |
| abstract data type/ˈæbstrækt ˈdeɪtə taɪp/ | абстрактный тип данных |
| stack/stæk/ | stack |
| linked list/lɪŋkt lɪst/ | связный список |
| LIFO/ˈlaɪfəʊ/ | LIFO |
| pop/pɒp/ | pop |
| pointer/ˈpɔɪntə/ | указатель |
| FIFO/ˈfaɪfəʊ/ | FIFO. |
| enqueue/enˈkjuː/ | enqueue |
| dequeue/diːˈkjuː/ | dequeue |
| node/nəʊd/ | узлом |
| traverse/trəˈvɜːs/ | обход |
The Back button and the printer queue
- Every page you visit is pushed onto a pile; the Back button takes the top one off. The page you left most recently is the first you return to.
- Down the corridor, a printer works through jobs in the order they arrived. The document sent first comes out first, however small the ones behind it.
- Two structures, opposite rules, and you use both before break. Neither says how it is stored; each says only what its operations do.
- That is an abstract data type 抽象数据类型. This lesson is the three the syllabus names, the operations on each, and how to justify one for a situation.
What an ADT is
- An abstract data type (ADT) is a collection of data together with a set of operations on that data. That one sentence is the one-mark definition.
- It is defined by what the operations do, not by how the data is stored. The implementation is hidden, so it can change without affecting the code that uses it.
- A stack, a queue, a linked list, a binary tree and an array are all ADTs.
Абстрактный тип данных (ADT) определяется:
ADT определяет операции (интерфейс); реализация скрыта и может изменяться произвольно.
The stack
- A stack 栈 is a list in which items are added to and removed from the same end, the top, so the last item added is the first removed: LIFO 后进先出.
- Operations: push 入栈 adds to the top, pop 出栈 removes from the top, peek looks at the top, and tests for empty and full.
- Uses: undo history, the Back button, the return addresses of function calls, checking brackets, backtracking.

Everything happens at the top
В каком порядке работает стек?
Стек работает по принципу LIFO: последний добавленный элемент является первым извлечённым.
Worked example: trace the stack
- A stack holds, from the bottom,
'P' 'N' 'Z' 'X' 'Y' 'W'; the top pointer is at'W'. The operationsPOP,POP,PUSH 'A',PUSH 'B',POPare performed. What does the stack hold, and where is the pointer? - The two pops remove
'W'then'Y'. The pushes put'A'then'B'in their places. The last pop removes'B'. - The stack holds
'P' 'N' 'Z' 'X' 'A', with the pointer at'A'. The item on the stack longest is the bottom one,'P'; five more pops are possible, and a sixth would be an error, which is why pop tests for empty first.
Стек содержит P N Z X Y W (верхний элемент — W). После операций POP, POP, PUSH 'A', PUSH 'B', POP какой элемент находится сверху?
Извлечены W и Y, затем добавлены A и B, после чего B удалён. Сверху находится A над X.
The queue
- A queue 队列 is a list in which items are added at the rear and removed from the front, so the first item added is the first removed: FIFO 先进先出.
- Operations: enqueue 入队 adds at the rear, dequeue 出队 removes from the front, and tests for empty and full.
- Uses: print spooling, keyboard buffers, scheduling, customers in a shop, breadth-first search.

Join at the back, leave from the front
Стеки, очереди и связные списки
LIFO против FIFO
Стек работает по принципу LIFO (последним пришёл — первым ушёл); операции PUSH и POP выполняются с одного конца (сверху).
Очередь работает по принципу FIFO: элементы извлекаются из ______ и добавляются сзади.
FIFO: dequeue с фронта, enqueue сзади — как очередь людей.
Worked example: describe adding to and removing from a queue
- Adding: check that the queue is not full; store the item at the position given by the rear pointer; move the rear pointer on (and add one to the count).
- Removing: check that the queue is not empty; read the item at the front pointer; move the front pointer on (and subtract one from the count).
- State the convention you use: if the rear pointer marks the next free space, store first and then move; if it marks the last item, move first and then store. Either scores, if you are consistent.
Расставьте шаги добавления элемента в очередь по порядку (указатель rear указывает на следующее свободное место).
Проверка выполняется первой; затем сохранение, затем перемещение, при таком порядке следования. Укажите используемую вами конвенцию.
The linked list
- A linked list 链表 is a list in which each node 节点 holds a data item and a pointer 指针 to the next node, with a start pointer to the first node. The last node's pointer is a sentinel such as
NULL. - Operations: insert, delete, search, and traverse 遍历, following the pointers from the head to visit every node in order.
- Advantage over an array: inserting or deleting is cheap, just rewire pointers, and the list grows as needed. Disadvantage: no random access; reaching the tenth node means following nine pointers.

A value and an arrow, repeated
Связный список: узлы соединены указателями.
Каждый узел хранит значение и указатель на следующий узел. Вставка или удаление только перенаправляют указатели — элементы не сдвигаются, в отличие от массива.
Каждый узел связного списка содержит:
Узел хранит свое значение плюс указатель (ссылку) на следующий узел; head обозначает начало, NULL — конец.
Связный список обеспечивает дешевую вставку/удаление (просто перенаправить указатели), но медленный случайный доступ (необходимо следовать указателям от head).
Это компромисс между массивом и списком: массивы обеспечивают доступ по индексу O(1); списки обеспечивают дешевую вставку/удаление.
Worked example: add a node in order
- Describe how a new value is inserted into a linked list that is kept in ascending order. [4]
- Traverse the list from the head, following the pointers, until the node before the position is found: the last node whose value is smaller than the new one.
- Take a free node and store the new value in it. Set the new node's pointer to the address the previous node currently points to.
- Then set the previous node's pointer to the new node. If the new value belongs at the front, it is the head pointer that changes instead.
Расставьте шаги вставки значения в упорядоченный связный список по порядку.
Найти, заполнить, направить новый узел вперед, затем перенаправить предыдущий узел. Изменение порядка последних двух шагов приведет к потере остальной части списка.
Justifying the choice
- Items must be handled in the order they arrived, print jobs, key presses, customers: a queue, because it is first in, first out.
- The most recent item must be handled first, undo, going back, nested calls: a stack, because it is last in, first out.
- Items are frequently inserted or deleted in the middle of an ordered collection, and the size is unknown: a linked list, because only pointers change and nothing is shifted.
- Name the structure, name its rule, tie the rule to the situation.
Соотнесите каждый ADT с его правилом и типичным использованием.
Стек = LIFO; очередь = FIFO; связный список цепляет узлы с помощью указателей.
Задания на печать должны быть выполнены в порядке их поступления. Какой ADT и почему?
Порядок поступления соответствует правилу FIFO. Стек напечатал бы самое последнее задание первым.
ADT versus implementation
- The ADT is the behaviour: push and pop, enqueue and dequeue, insert and traverse.
- The implementation is the storage: in this course, an array plus a few pointer variables (next lesson).
- A question about the ADT wants operations and rules; a question about implementation wants arrays, pointers and the checks.
Marks that slip away
- Push and enqueue test for full first; pop and dequeue test for empty first. Write the check into the description.
- Inserting into a linked list: set the new node's pointer before changing the previous node's, or the rest of the list is lost.
- A stack changes at one end, a queue at both. "Remove from the top of the queue" is a stack answer.
- Expand the abbreviations once: LIFO, last in first out; FIFO, first in first out.
You've got it
- an ADT is a collection of data together with a set of operations on it; behaviour, not storage
- stack: add and remove at the top, LIFO, push and pop · queue: add at the rear, remove at the front, FIFO, enqueue and dequeue
- linked list: nodes of value + pointer from a head pointer; cheap insert and delete, slow random access; traverse by following pointers
- justify by rule: order of arrival → queue; most recent first → stack; frequent insertion in the middle → linked list