def insert(self, index, value): if index < 0 or index >= self.size: return new_node = Node(None, value) if index == 0: new_node.set_next(self.head) self.head = new_node self.size += 1 return current = self.head while index - 1 is not 0: current = current.get_next() index -= 1 current_next = current.get_next() new_node.set_next(current_next) current.set_next(new_node) if new_node.get_next() is None: self.tail = new_node self.size += 1
def add(self, item): current = self.head previous = None stop = False while current is not None and not stop: # Make use of sorted property to stop traversal early if current.get_data() > item: stop = True else: previous = current current = current.get_next() node = Node(item) # if item has to be inserted in first position # i.e. previous is None, reset head to new item if previous is None: node.set_next(self.head) self.head = node # Normal case: prev to item, item to current else: previous.set_next(node) node.set_next(current)
def insert(self, item, pos): node = Node(item) current = self.head previous = None index = 0 while current.get_next() is not None: if index == pos: if previous is not None: previous.set_next(node) node.set_next(current) else: node.set_next(current) self.head = node return else: previous = current current = current.get_next() index += 1 # If item is to be inserted at the last index previous.set_next(node) node.set_next(None)
def add(self, item): # add item to first item (i.e. head) # reset head to point to the new first item in the list temp = Node(item) temp.set_next(self.head) self.head = temp