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:

stores a value
retrieve the n-th value stored
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)

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): = data = None

class LinkedList:
    def __init__(self):
        self.first = None

    def append_to(self, node: ListNode, data):
        if not
   = ListNode(node, data)
            self.append_to(, data)

    def append(self, data):
        if not self.first:
            self.fst = ListNode(data)
            self.append_to(self.first, data)