In this post, we will see how to create a Linked List of 3 nodes in Python.
Logic:
For creating a Linked List of 3 Nodes. We would first need to create 3 Nodes and then point next of Node1 to Node2, next of Node2 to Node3.
Implementation Steps:
- Create a Node class with the constructor.
- Create a 3 Objects of Node class with given values.
- Assigning the next Node references to the current Node.
let’s see the code implementation:
# Define a Node class class Node: # Define a constructor for # initializing data and nextRef # member values # d : data # self : refer to current object def __init__(self, d) : self.data = d self.nextRef = None # Main code if __name__ == "__main__" : # Create a Node object # with given data node1 = Node(10) # print(node1.data) node2 = Node(20) node3 = Node(30) # Assigning references node1.nextRef = node2 node2.nextRef = node3 # print(node1.data) # print(node1.ref) # point head to starting # node of linked list head = node1 temp = head print("Data in 3 node Linked List are: ") # Traversing through nodes # of Linked List while temp != None : # print the data of nodes print(temp.data, end = " ") # move to next node temp = temp.nextRef
Output:
Data in 3 node Linked List are: 10 20 30
Thanks for reading this Post.