def insert(head, index, value): if index < 0: return head if not head and index > 0: return head if index == 0: new = Node(value=value) new.next = head head = new return head node = head prev = None step = 0 while node and step < index: prev = node node = node.next step += 1 if not node: return head next = prev.next new = Node(value=value) prev.next = new new.next = next return head
def insert_before_value(self, value, x): ''' This function is used to add element before given value params: value: any type x : any type ''' if self.head is None: raise Exception("List has no items") new_node = Node(value) # if first node has matched condition if self.head.data == x: new_node.next = self.head self.head = new_node return prev = self.head while prev: if prev.next.data == x: break prev = prev.next if prev is None: raise Exception("{} not exists in list".format(x)) new_node.next = prev.next prev.next = new_node
def push(self, value): ''' This function is used to add element at the beginning params: value: any type ''' new_node = Node(value) new_node.next = self.head self.head = new_node return
def insert_after_value(self, value, x): ''' This function is used to add element after given value params: value: any type x : any type ''' if self.head is None: raise Exception("List has no items") new_node = Node(value) current = self.head while current: if current.data == x: break current = current.next if current is None: raise Exception("{} not exists in list".format(x)) new_node.next = current.next current.next = new_node