Implementing (linked) lists in Python ------------------------------------- Here is a slightly different, and possibly cleaner, way to implement flexible lists using Python classes. Instead of having a single class to represent nodes in the list, we have two classes: 1. class List This will define a "header" node for each list. It has one attribute, which we shall call head. If self.head is None, the list is empty, otherwise self.head points to the first real node in the list. 2. class Node These have two internal attributes, value and next, as in the earlier implementation. However, value is never None and next is None only for the last node in the list. Thus, a list with two values [7,8] would look as follows, List Node ------------ ----------------- | | | | | | l --> | head | o--+--->| value | 7 | | | | | | | Node ------------ --------+-------- ----------------- | | | | | | | next | o----+---->| value | 8 | | | | | | | ----------------- --------+-------- | | | | next | None | | | | ----------------- while an empty list would just look like this: List ------------- | | | l --> | head | None | | | | ------------- The header node allows us to represent an empty list more cleanly than with only one type of node, where a node with value == None indicates an empty list. In this new representation, we can define append, insert and delete more neatly: ---------------------------------------------------------------------- append (recursive): In List: if self.head is None # List is empty make self.head point to a new Node with value x else append x into self.head In Node: if self.next is empty # last node make self.next point to a new Node with value x else append x into self.next ---------------------------------------------------------------------- insert: In List: if self.head is None # List is empty make self.head point to a new Node with value x else create newnode with value x set newnode.next to self.head set self.head to newnode ---------------------------------------------------------------------- delete (recursive): In List: if self.head is not None # List is not empty if self.head.value is x # first node is to be deleted set self.head to self.head.next else delete x from self.head In Node: if self.next is not None if self.next.value is x # next node is to be deleted set self.next to self.next.next else delete x from self.next ---------------------------------------------------------------------- The iterative versions of append and delete can also be defined more cleanly --- see the sample code that is attached. Note that we have functions append/delete defined both in the class List and in the class Node: typically the version in List only handles the special case of the empty list and the real work is done inside Node. ======================================================================