Why does self.head = None remove every element in a linked list?

Viewed 23

I am learning about linked lists for the first time and feel like I am getting a pretty good understanding of inserting at the beginning or end of a linked list.

However, I see that if I have an existing linked list and I do self.head = None then it gets rid of every element, thus giving me an empty linked list. What is happening under the hood? Why does this happen? Any information is appreciated.


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


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

    def insert_at_beginning(self, data):
        node = Node(data, self.head)
        self.head = node
    
    def print(self):
        if self.head is None:
            print("linked list is empty")
            return
        
        itr = self.head
        llstr = ''
        while itr:
            llstr += str(itr.data) + '-->'
            itr = itr.next
        
        print(llstr)

    def insert_at_end(self, data):
        if self.head is None:
            self.head = Node(data, None)
            return
        
        itr = self.head
        while itr.next:
            itr = itr.next

        itr.next = Node(data, None)

    def clear_linked_list(self):
        self.head = None
        return

    def insert_values(self, data_list):
        self.clear_linked_list()
        for data in data_list:
            self.insert_at_end(data)


if __name__ == "__main__":
    ll = LinkedList()
    ll.insert_at_beginning(5)
    ll.insert_at_beginning(89)
    ll.insert_at_end(90)
    ll.print()
    ll.insert_values(['nothing', 'test'])
    ll.print()
1 Answers

If you're familiar with scavenger hunt-type games, you find the location of the next clue only when you solve a clue. You get the location of the first clue at the start of the game. What if I never gave you the first clue? Would you be able to play the game?

In a linked list, each node contains a reference to the next node. Setting self.head is equivalent to giving you the first clue. If you get rid of the first node, there's no way to know which is the second node because that information was only in the first node which you just got rid of.

Related