You often want to know the number of items in a linked list. In the code below (which is copied from the chapter), add a method length()
to SingleLinkedList
which returns the number of items in the chain. Make sure that it is O(1)
.
class SingleNode:
def __init__( self, value, nextnode ):
self.value = value
self.nextnode = nextnode
class SingleLinkedList:
def __init__( self ):
self.head = None
def add( self, value ):
node = SingleNode( value, self.head )
self.head = node
def remove( self ):
if self.head != None:
self.head = self.head.nextnode