def add(self, data): """Create a new Node containing 'data' and add it to the end of the list. Example: >>> my_list = LinkedList() >>> my_list.add(1) >>> my_list.head.data 1 >>> my_list.add(2) >>> my_list.head.next.data 2 """ new_node = LinkedListNode(data) if self.head is None: # If the list is empty, point the head attribute to the new node. self.head = new_node else: # If the list is not empty, traverse the list # and place the new_node at the end. current_node = self.head while current_node.next is not None: # This moves the current node to the next node if it is not # empty. Then when we break out of the loop, current_node # points to the last node in the list. current_node = current_node.next current_node.next = new_node
def insert_node(self, new_data, old_data): #check to see if it's empty if self.head is None: return #if inserting at the front of the list new_node = LinkedListNode(new_data) if old_data == self.head.data: new_node.next = self.head self.head = new_node return else: current_node = self.head while current_node.next.data != old_data: current_node = current_node.next if current_node.next is None: print "Node not in list" return new_node.next = current_node.next current_node.next = new_node
def __init__(self, data): Node.__init__(self, data) self.prev = None