An unordered list consists of an initial "head" of the list which may point to a Node
, which in turn may point to other Node
objects which collectively make up the entire list.
Write an UnorderedList
class that begins with this constructor:
import Node
class UnorderedList(object):
"""Maintains an unordered list via a linked series of Nodes
"""
def __init__(self):
self.head = None
Then continue developing the the class by writing the following methods:
add(item)
allows us to add an item to the beginning of the list. (For the moment, we're going to assume it's a unique item, and that it's not already present on the list.)remove(item)
removes the specified item from the list. This assumes that the item is already in the list.search(item)
looks for the specified item in the list, and returns True it if is there somewhere.is_empty()
returns True if the list is empty.length()
returns the number of items in the list.append(item)
adds the item to the end of the list.index(item)
returns the position of the item in the list (and assumes it is in the list)insert(pos, item)
adds a new item to the list at the specified position. This assumes that the item is not already on the list and that the position exists.pop()
removes the last item from the list and returns it.pop(pos)
removes the item at the specified position and returns it.In addition to these methods, it will certainly be helpful to you to have a __repr__
method that you can use to print out the state of your unordered list.
def __repr__(self):
"""Creates a representation of the list suitable for printing,
debugging.
"""
result = "UnorderedList["
next_node = self.head
while next_node != None:
result += str(next_node.get_data()) + ","
next_node = next_node.get_next()
result = result + "]"
return result