简体   繁体   中英

Recursively add to an ordered linked list

I'm trying to create an add function to add recursively to an ordered linked list and cannot seem to get started. I'm given the two functions

    def add(self, item):
        new_node = Node(item)
        curr = self.__head
        prev = None
        self.add_recursive(new_node, curr, prev)

    def add_recursive(self, new_node, curr, prev):
            pass

I know how to add to an ordered linked list in a traditional method but can't seem to wrap my head around how to do it by calling it in this manner as well as with recursion. Other functions that can be used in this class are .is_empty() and .size()

Thank you

When it comes to hierarchical structures (such as trees), the human brain can easily visualise recursion (we think recursively), but with flat structures like linked lists, this admittedly seems harder to do so.

Let's break this down. At what point should we add a node? Certainly, when we know there are no nodes in front of curr . At this point, you'd assign curr.next = new_node and return. Until then, you advance curr and continue. This is what happens in the iterative sense as well.

Putting this understanding into code, you'd have

def add_recursive(self, new_node, curr, prev):
    """ note that we aren't yet taking care of the case when head is None """
    if not curr.next:                
        curr.next = new_node
        return

    return self.add_recursive(new_node, cur.next, cur)

One important consideration is the corner case when you are inserting for the firs time. In which case, you'd call .is_empty or size and check if the linked list has any elements or not, and accordingly assign self.head = new_node :

if self.is_empty():
    self.head = new_node
    return

This is the first check that must be done. So, your full function now becomes:

def add_recursive(self, new_node, curr, prev):
    if self.is_empty():
        self.head = new_node
        return

    elif not curr.next:                
        curr.next = new_node
        return

    return self.add_recursive(new_node, cur.next, cur)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM