def push(self, value): new_top = Node(value) if self.top is None: self.top = new_top else: new_top.next = self.top self.top = new_top
def add_first(self, node: Node) -> None: """ Add a new node as the first position in the linked list :param node: (Node) The new node instance to add the linked list :return: void """ node.next = self.head self.head = node
def insert_after(self, node, value): n = self.head while n.next is not None: if n == node: new_node = Node(value) new_node.next = n.next n.next = new_node return n = n.next
def __init__(self, nodes: Optional[List] = None) -> None: """ This is called when a new LinkedList object is instantiated :param nodes: (list) The start list (default None) """ self.head = None if nodes is not None: node = Node(data=nodes.pop(0)) self.head = node for elem in nodes: node.next = Node(data=elem) node = node.next
def insert(self, pos, value): node = self.head index = 0 while node: if index == pos - 1: new_node = Node(value) new_node.next = node.next node.next = new_node return True node = node.next index += 1 return False
def add_after(self, target_node_data: Any, new_node: Node) -> None: """ Add a new node after the given target value from the linked list :param target_node_data: The target data value :param new_node: (Node) The new node instance to add after the given target value from the linked list :return: void :raises: Exception: List is empty Exception: Node with data '%s' not found """ if not self.head: raise Exception("List is empty") for node in self: if node.data == target_node_data: new_node.next = node.next node.next = new_node return raise Exception("Node with data '%s' not found" % target_node_data)