Beispiel #1
0
    def insert_at_position(self, position, data):
        """ Position is 1 based. """
        if self.head is None:
            raise EmptyListError("List is empty, can't insert.")

        list_length = self.get_length()
        if not (1 <= position <= list_length + 1):
            raise RangeError(
                "Position range must be 1 through {0}.".format(list_length +
                                                               1))

        if position == 1:
            self.insert_at_beginning(data)
        elif position == list_length + 1:
            self.insert_at_end(data)
        else:
            pointer = self.head
            pos = 1
            while pos != position - 1:
                pointer = pointer.get_next()
                pos += 1

            node = NodeCircular(data)
            node.set_next(pointer.get_next())
            pointer.set_next(node)
Beispiel #2
0
def nth_node_from_end(linked_list, n):
    """
    Find nth node from end of a linked list (assume positions as 1 based).
    Hint: For a linked list of size m, nth node from end would be
    (m - n + 1)th node from beginning.

    :param SingleLinkedList linked_list: The linked list to operate.
    :param int n: The position from end.
    :return: the data of the node.
    :rtype: int
    :raises EmptyListError: if the list is empty.
    :raises RangeError: if length of list < n < 0.
    """

    list_length = linked_list.get_length()
    if list_length == 0:
        raise EmptyListError("List is empty, can't find node")

    if not (1 <= n <= list_length):
        raise RangeError("Position range must be 1 through {0}".format(list_length))

    nth_from_end = list_length - n + 1
    pointer = linked_list.head
    position = 1

    while position != nth_from_end:
        pointer = pointer.get_next()
        position += 1

    return pointer.data
Beispiel #3
0
    def delete_at_position(self, position):
        """ Position is 1 based. """
        if self.head is None:
            raise EmptyListError("List is empty, can't delete.")

        list_length = self.get_length()
        if not (1 <= position <= list_length):
            raise RangeError(
                "Position range must be 1 through {0}.".format(list_length))

        if position == 1:
            self.delete_at_beginning()
        else:
            pointer = self.head
            pos = 1
            while pos != position - 1:
                pointer = pointer.get_next()
                pos += 1

            next = pointer.get_next().get_next()
            pointer.get_next().set_next(None)
            pointer.set_next(next)