Linked lists · 연결된 리스트
Nodes joined by links
- A linked list is a chain of nodes.
- Each node holds a piece of data and a link to the next node.
- The last node links to
None, which marks the end.
A node is a small record
- We can store one node in a dictionary:
{"data": ..., "next": ...}. "data"holds the value;"next"holds the next node (orNone).- The first node is called the head of the list.
second = {"data": "b", "next": None}
first = {"data": "a", "next": second}
print(first["data"])
print(first["next"]["data"])
Walk the list
- Start at the head and follow each
"next"link. - Stop when you reach
None. - This visiting of every node is called traversal.
head = {"data": 1, "next": {"data": 2, "next": None}}
node = head
while node is not None:
print(node["data"])
node = node["next"]
Why a linked list?
- You can insert or remove a node by changing links — no shifting of items.
- An array would have to move every item after the change.
- But a linked list has no index: to reach item 5 you must walk from the head.
In Cambridge pseudocode
- The exam stores nodes in an array;
Nextis the index of the next node, andNULLmarks the end.
TYPE Node
DECLARE Data : INTEGER
DECLARE Next : INTEGER // index of the next node, or NULL
ENDTYPE
current ← head
WHILE current <> NULL
OUTPUT list[current].Data
current ← list[current].Next
ENDWHILE
Common mistakes
- Never lose the
headpointer, or the whole list is unreachable. - The last node points to
None.
Now you try
- A node is a dict
{"data": ..., "next": ...}. Follow"next"to walk the chain. - Press Check answer to test your code.
Nodes linked by pointers · 포인터로 연결된 노드
Each node points to the next; you insert/delete by re-linking. · 각 노드는 다음 노드를 가리키며, 삽입/삭제는 **재연결(re-linking)**을 통해 수행합니다.
Build a linked list 1 → 2 → 3 using dictionaries. Make the three nodes, link each to the next, and point head at the first one. The last node's "next" must be None. · 사전을 사용하여 연결된 리스트 1 → 2 → 3을 만드세요. 세 개의 노드를 만들고 각각 다음 노드와 연결하며, head을 첫 번째 노드를 가리키게 하세요. 마지막 노드의 "next"은 반드시 None이어야 합니다.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Walk the linked list starting at head and add up every node's "data". Store the total in total (the answer is 60). · head에서 시작하여 연결된 리스트를 traversal하며 각 노드의 "data"을 모두 더하세요. 총합을 total에 저장합니다 (정답은 60).
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Write length(head) that returns how many nodes are in the linked list. An empty list (head is None) has length 0. · length(head)을 작성하여 연결된 리스트에 있는 노드의 개수를 반환하세요. 빈 리스트(head이 None인 경우)의 길이는 0입니다.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.