示例#1
0
    def insert(
        self, index, data
    ):  #runs in O(n) time. #we are inserting the data at the index you assign to.
        newNode = ListNode(data, None, None)
        itrNode = self.__start
        counter = 1
        while (
                counter < index
        ):  # we are going to loop based on where we want to insert the new node
            itrNode = self.__start.getNext()
            # this iteraters through each node
            counter = counter + 1  # we are keeping track of whwere the index is in the linked list.

        if (index == 0):
            self.push_front(data)
        elif (index > self.__length):
            self.push_back(data)
        else:
            #A in the code will be itrNode
            #B in the code will be itrNode.getPrevious();
            A = itrNode
            B = itrNode.getPrevious()
            newNode.setPrevious(B)
            newNode.setNext(A)
            B.setNext(newNode)
            A.setPrevious(newNode)