A faster append operation

There is a big problem with the append method in the previous section: it has to traverse the entire list to find the insertion point. This may not be a problem when there are just a few items in the list, but it will be a big problem when the list is long, as we would need to traverse the whole list to add an item every time. Each append will be slightly slower than the previous one. The current implementation for the append operation is slowed down by  O(n), which is not desirable in the case of a long list.

To fix this, we store not only a reference to the first node in the list but also a reference to the last node. That way, we can quickly append a new node at the end of the list. The worst-case running time of the append operation is now reduced from O(n) to O(1). All we have to do is make sure the previous last node points to the new node that is about to be appended to the list. Here is our updated code:

class SinglyLinkedList:
def init (self):
# ...
self.tail = None

def append(self, data):
node = Node(data)
if self.head:
self.head.next = node
self.head = node
else:
self.tail = node
self.head = node

Take note of the convention being used. The point at which we append new nodes is through self.head. The self.tail variable points to the first node in the list.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset