Linked lists
So far, we’ve mostly used objects to represent real-world entities (animals, stars, etc.). We can also use objects to implement data structures.
Let’s say we want a data structure that has the following operations:
- append(value)
- stores a value
- nth(n)
- retrieve the n-th value stored
- remove(n)
- remove the nt-th value stored
These operations should sound familiar: they are the core operations on Python’s lists. We saw a similar type in Pyret: Pyret’s lists, defined as
data List: | empty | link(fst, rst :: List) end
Python’s lists are implemented using contiguous chunks of memory. Pyret’s lists are different: they are constructed as a linked structure. Could we build something similar in Python? Yes! See the lecture capture for details. Here’s what we developed in class:
class ListNode: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.first = None def append_to(self, node: ListNode, data): if not node.next: node.next = ListNode(node, data) else: self.append_to(node.next, data) def append(self, data): if not self.first: self.fst = ListNode(data) else: self.append_to(self.first, data)