Search code examples
pythonrangedoubly-linked-list

Add a range function in my DVL class to doubly linked list in python


I am currently looking at doubly linked list in python and I am stuck with the following problem: I want to create a range function - range(start, stop, step) - which should give me all values starting at position start to position stop. If a value step is passed, then the steps are to be taken into account. Right now I only have the basics for the doubly linked lists, it would be great if you could help me out. Thank you in advance

class Node:
    def __init__(self, value):
        self.value = value
        self.next = None
        self.previous = None

class DVL:
    def __init__(self):
        self.first = None
        self.last = None


    def add(self, value):
        new_node = Node(value)

        if self.last == None:
            # add first node
            self.last = new_node
            self.first = new_node
        else:
            new_node.previous = self.last
            self.last.next = new_node
            self.last = new_node

    def print_forward(self): 
        node = self.first
        while(node is not None): 
            print(node.value) 
            node = node.next

Solution

  • I haven't tested this but you can think along the same lines.

    I have assumed that start < end and step >= 1. the code can be modified for generic range function.

    def _skip_n(self, node, n):
        count = 0
        while count <= n:
            node = node.next
            count += 1
    
        return node
    
    def range(self, start, end, step):  # assumes end is less than or equal to length of the list
        res = []
        node = self.first
        for i in range(start, end, step):
            res.append(node.value)
            node = self._skip_n(node, step)
    
        return res