More lists

How programs with objects execute

As a reminder, here’s our linked list code from last time.

class ListNode:
    def __init__(self, data, parent=None):
        self.data = data
        self.parent = parent
        self.next = None

class LinkedList:
    def __init__(self):
        self.fst = 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.fst:
            self.fst = ListNode(data)
        else:
            self.append_to(self.fst, data)

    def find_nth_after(self, node: ListNode, n: int) -> ListNode:
        if not node:
            raise IndexError("Index out of bounds")
        if n == 0:
            return node
        return self.find_nth_after(node.next, n - 1)

    def find_nth(self, n: int) -> ListNode:
        return self.find_nth_after(self.root, n)

    def nth(self, n: int):
        return self.find_nth(n).data

    def remove_node(self, node):
        if node.parent:
            node.parent.next = node.next
        if node.next:
            node.next.parent = node.parent

    def remove(self, index: int):
        self.remove_node(self.find_nth(index))

What happens when we execute this code?

lst = LinkedList()
lst.append(10)
lst.append(15)
lst.append(20)

When this code is done executing, memory looks like this:

name value
lst loc 1
location data
loc 1 LinkedList { first -> loc 2 }
loc 2 ListNode { data -> 10, parent -> None, next -> loc 3 }
loc 3 ListNode { data -> 15, parent -> loc 2, next -> loc 4 }
loc 4 ListNode { data -> 20, parent -> loc 3, next -> None }

Removing nodes

How about removing nodes? Will the following code get rid of the second node in the list?

lst.remove_node(ListNode(5))

It wouldn’t–it would try to modify the parent and next fields of a disconnected ListNode, which wouldn’t actually do anything! What would memory look like if we actually removed the second ListNode in the list?

name value
lst loc 1
location data
loc 1 LinkedList { first -> loc 2 }
loc 2 ListNode { data -> 10, parent -> None, next -> loc 3 }
loc 3 ListNode { data -> 15, parent -> loc 2, next -> loc 4 }
loc 4 ListNode { data -> 20, parent -> loc 2, next -> None }