In Python, one way to implement a linked list is as a sequence class, as discussed in the chapter on operator overloading. Implement a single-linked list as a sequence class. Implement addhead()
and addtail()
methods to add an item to the start and the end of the linked list, respectively. Implement a pop()
method to remove the first item of the linked list and return its value. For the __getitem__()
and __setitem__()
methods, the key is the index of the item in the linked list. Also implement the __contains__()
and __len__()
methods. Implement a __repr__()
method to display the contents of the linked list. Note that, by using this implementation, you can now use a for ... in ...
construction to traverse the linked list (as well as using indices).
Build ontop of the code previously given:
class SingleNode:
def __init__( self, value, nextnode ):
self.value = value
self.nextnode = nextnode
class SingleLinkedList:
def __init__( self ):
self.head = None
self.tail = None
def add( self, value ):
node = SingleNode( value, self.head )
self.head = node
if self.tail == None:
self.tail = self.head
def remove( self ):
if self.head == self.tail:
self.head = None
self.tail = None
else:
self.head = self.head.nextnode
def append( self, value ):
node = SingleNode( value, None )
if self.tail == None:
self.head = node
self.tail = node
else:
self.tail.nextnode = node
self.tail = node
Note: The submission of this exercise is in markdown and therefore won’t be tested. Use your preferred code editor or Papyrus1 to test your code.