コード例 #1
0
    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
コード例 #2
0
    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
コード例 #3
0
    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
コード例 #4
0
    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
コード例 #5
0
    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
コード例 #6
0
    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)