Data structures and algorithms · Lesson 20 of 60 · Code lesson, JavaScript or Python · Optional
Linked lists
A linked list is a chain of nodes, and each node holds a value and a link to the next node.
The last node links to nothing (null or None), which is how you know the chain has ended.
To visit every node you start at the head and keep following the links.
Worked example
In JavaScript, a while loop that runs until current is null is the usual way to walk a chain.
class Node {
constructor(value, next = null) {
this.value = value;
this.next = next;
}
}
const head = new Node("a", new Node("b", new Node("c")));
console.log(head.next.value);Output: b
In Python, a while loop that runs until current is None is the usual way to walk a chain.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
head = Node("a", Node("b", Node("c")))
print(head.next.value)Output: b
Your turn
The program builds a linked list from the words it reads but only prints the first one. Walk the chain by following next links, and print every value on its own line.
Your program is checked with these 3 inputs:
Input:
1 2 3
Expected output:
1 2 3
Input:
7
Expected output:
7
Input:
4 5
Expected output:
4 5
Loading your practice…
Preparing your workspace…