1
\$\begingroup\$

Given a Singly Linked-List, write a function to delete the linked list recursively. Below is my attempt. I am confused if I should use del keyword to delete the nodes or below method is better. I don't know if it is memory efficient this way.I'd appreciate any critique of what I could do better.

class SLLNode:
    def __init__(self, data):
        self.data = data
        self.next = None

class SLL:
    def __init__(self):
        self.head = None

    def append(self, data):
        temp = SLLNode(data)
        if self.head is None:
            self.head = temp
        else:
            current = self.head
            while current.next is not None:
                current = current.next
            current.next = temp

def delete_a_linked_list_using_recursion(head):
    if head is None:
        return head
    head = head.next
    return delete_a_linked_list_using_recursion(head)

"""driver's code"""
sll = SLL()
sll.append(1)
sll.append(2)
sll.append(3)
sll.append(4)

head = delete_a_linked_list_using_recursion(sll.head)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.