Reputation: 29
I am new with data structures and just started with the linked list. I understand the whole code but I am unable to understand why
llist.head
is an attribute of class Linkedlist that becomes an object of class Node
. In a later example why we do this assignment llist.head = node(1)
?
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
if __name__=='__main__':
llist = LinkedList()
llist.head = Node(1)
second = Node(2)
third = Node(3)
llist.head.next = second
second.next = third
Upvotes: 2
Views: 1461
Reputation: 1
I have had the same question but wasn't much convinced. So, i did some research and found the precise answer for the question, Why do we create a different class for Node and head as well, i.e. Why do we use two classes in Linked List implementation ? These were all the questions i had and they all have a single answer:
Suppose we are only using the Node class i.e. no separate class for head node. And we always access the Linked List through a reference to the head node. What if multiple objects need a reference to the Linked List and then the head of the Linked List changes ? Some objects might still be pointing to the old head. What would we do ? 🤔. The solution to this problem is the introduction of the LinkedList class containing the head node i.e. saving the initial value of head node. So we should implement a LinkedList class that wraps the class Node.
Upvotes: 0
Reputation: 350
It's very common to have other objects as attributes to a class!
(Especially in Python it makes sense to think of all attributes of a class as objects. A number might be an Integer object, a name is a String object... And a LinkedList has Node objects. The only difference here is that you created the class yourself instead of using a built-in class!)
Using separate classes for Node and LinkedList makes a lot of sense in an object oriented approach. They are very different things, that have some kind of correlation, similar to, let's say, bus line and bus stop. The bus line has a first, second and third stop etc. The stops themselves have a previous and next stop.
BTW: Part of the beauty of a LinkedList is that you don't have to name every node. You only need to know where it starts - and from there onwards, you simply follow the individual node's next
element to get all the way through the list.
Upvotes: 0
Reputation: 3437
You have a class representing a node and a class representing a list.
But you can also consider that each node represents the starting point of a (sub)list. So you can do away with the class representing the list if it suits you better:
class Node:
def __init__(self, data):
self.data = data
self.next = None
if __name__ == '__main__':
head = Node(1)
second = Node(2)
third = Node(3)
head.next = second
second.next = third
Upvotes: 2