Home首页 / Lesson 2: Linked list第 2 课:链表
Lesson 2 · Data structure第 2 课 · 数据结构
What is a linked list?什么是链表?
Boxes that hold hands. Each one knows only where the next one is.手拉手的一串盒子,每个只知道自己右边是谁。
01The idea先有一个画面
A linked list is that chain of notes. Each box is a node. A node holds:链表就是这一串纸条。每个盒子叫 node(节点),里面装两样东西:
- the value值(要存的东西)
- the pointer to the next node指向下一个节点的指针
02Array vs linked list数组和链表差在哪
| Array数组 | Linked list链表 | |
|---|---|---|
| Where the boxes are盒子在哪 | next to each other紧挨着 | anywhere, joined by pointers随便放,用指针连起来 |
| Read number 500读第 500 个 | O(1) one stepO(1),一步 | O(n) walk 500 nodesO(n),要走 500 个 |
| Insert in the middle中间插入 | O(n) move everything afterO(n),后面全要挪 | O(1) change two pointersO(1),改两个指针 |
| Memory内存 | needs one full block要一整块连续内存 | any small blocks小块内存就行 |
03Why it is used in HashMap为什么 HashMap 里要用它
Two different keys can land in the same bucket. The simplest fix is to keep them in a short linked list: put the new one at the end, and when you look up a key, walk the list and compare keys.两个不同的 key 可能落进同一个桶。最简单的办法就是把它们串成一条短链表:新的放末尾,查找时顺着链走、逐个比 key。
That is why the array inside a HashMap is called an “array of buckets”: each cell holds the head of a small list.所以 HashMap 里的数组叫“桶数组”:每一格存的是那条短链的头。
04Where you meet it你会在哪里遇到它
- HashMap: one bucket = one short list (lesson 4).HashMap:一个桶就是一条短链(第 4 课会讲)。
- A queue of tasks with a pointer to the next: a linked list.任务队列:每个任务指向下一个,本质就是链表。
→New words新词
Click ▶ hear it for real people on YouGlish; 🔊 for the computer voice.点 ▶ hear it 听真人发音(YouGlish);点 🔊 听电脑朗读。
✓Check yourself自测
- Why can I not jump to the 500th item?为什么不能直接跳到第 500 个?
- Insert in the middle: array or linked list? Why?中间插入:数组还是链表?为什么?
- What does the last pointer hold?最后一个节点的指针指向什么?
Answer out loud first. Only then open the answers below.先自己出声答,再看下面的答案。