Creation of Linked List in Python

Creation of Linked List in Python

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.

Leave a Reply

Your email address will not be published.

📢 Need further clarification or have any questions? Let's connect!

Connect 1:1 With Me: Schedule Call


If you have any doubts or would like to discuss anything related to this blog, feel free to reach out to me. I'm here to help! You can schedule a call by clicking on the above given link.
I'm looking forward to hearing from you and assisting you with any inquiries you may have. Your understanding and engagement are important to me!

This will close in 20 seconds