Bitpath

Lesson 1 · Unit 03

Nodes and pointers

A chain you can only enter at the head

12 exercisesabout 3 min

What you practise

  • A node class (generic in TS), traversal, O(1) insert at the head, O(n) indexing

Try a question from this lesson

Pick one

In a treasure hunt, each clue only tells you where the next clue is. You hold clue 1. How do you get to read clue 5?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

A node: a value and a pointer

A linked list is made of nodes. Each node holds a value, val, and a pointer to the node after it, next. The last node's next is empty.

You keep one variable, the head. Everything else is reached from it.

class Node:
    def __init__(self, val, next=None):
        self.val = val
        self.next = next

head = Node(3, Node(5))   # 3 -> 5
print(head.val, head.next.val)
class Node {
  constructor(val, next = null) {
    this.val = val;
    this.next = next;
  }
}
const head = new Node(3, new Node(5));
console.log(head.val, head.next.val);
class Node<T> {
  constructor(
    public val: T,
    public next: Node<T> | null = null,
  ) {}
}
const head = new Node(3, new Node(5));
console.log(head.val, head.next!.val);

Python notenext=None is a default: Node(5) makes a node that points to nothing.

JavaScript notenext = null in the parameter list is a default value, used when the caller passes one argument.

TypeScript notepublic val: T in a constructor declares the field and assigns it in one go. Node<T> | null says the pointer may be empty, so head.next! is needed before .val.

Concept

A new head costs one node

To add at the front, make one node that points at the old head. That node is the new head. Nothing else moves: O(1), however long the list is.

The function returns the new head, so the caller must store it.

def push_front(head, val):
    # the new node points at the old head
    return Node(val, head)
function pushFront(head, val) {
  // the new node points at the old head
  return new Node(val, head);
}
function pushFront<T>(
  head: Node<T> | null,
  val: T,
): Node<T> {
  // the new node points at the old head
  return new Node(val, head);
}

TypeScript note<T> makes the function generic: it works for a list of any type, and val must match the type the list already holds.

9 more exercises in the app

  • 3× type the answer
  • 1× order the lines
  • 2× multiple choice
  • 1× fill the blanks
  • 1× true or false
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy