Linked Lists
56 / 170Linked ListsLesson 1 of 12About 63 min
Every linked list bug is the same bug: you overwrote the only reference to something.
Walking a list is one shape, and while node: is the idiomatic condition because None is falsy. Using while node is not None: is equally correct and a little more explicit.
class Node: def __init__(self, val, next=None): self.val, self.next = val, next def build(values): head = None for value in reversed(values): head = Node(value, head) return head def to_list(node): out = [] while node: out.append(node.val) node = node.next return out node = build([3, 1, 4])total = 0while node: total += node.val node = node.nextprint(total)This tries to reverse the first two nodes and loses part of the list. Type what it prints.
class Node: def __init__(self, val, next=None): self.val, self.next = val, next def to_list(node): out = [] seen = 0 while node and seen < 10: out.append(node.val) node = node.next seen += 1 return out third = Node(3)second = Node(2, third)first = Node(1, second) second.next = firstfirst.next = None print(to_list(second))Three loops that all carry a predecessor. count_nodes returns the length. remove_at removes the node at a given index, doing nothing if the index is out of range. swap_first_two swaps the first two nodes by relinking, not by swapping values.
Tests
print(count_nodes(build([1, 2, 3])), count_nodes(build([])))print(to_list(remove_at(build([1, 2, 3]), 0)), to_list(remove_at(build([1, 2, 3]), 2)))print(to_list(remove_at(build([1, 2, 3]), 9)))print(to_list(swap_first_two(build([1, 2, 3]))), to_list(swap_first_two(build([1]))))Output
Run tests to see output.
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.