Implementation of Linked List in Python

Implementation of Linked List in Python

In this post, We will see the implementation of Linked-List in python.

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
        
# Define a traversal method
# for traversing each node
# of the Linked List
def traversal(head) :

    temp = head
    while(temp != None) :
        
        print(temp.data,end = " ")
        temp = temp.nextRef

# Define a deletion method
# for deleting any node
# of Linked List
def deletion(data, head) :

    if head.data == data :
        head = head.nextRef
        return head
    else:
        temp = head
        prev = None

        while temp != None :
            if temp.data == data :
                prev.nextRef = temp.nextRef
                temp.nextRef = None
                return head
            else :
                prev = temp
                temp = temp.nextRef
                
        return head

# Define an insertion method
# for inserting nodes in
# the Linked List
def insert(head, data, pos) :

    if pos == 0 :
        newNode = Node(data)
        newNode.nextRef = head
        head = newNode
        return
    else :
        
        newNode = Node(data)
        i = 0
        temp = head

        while temp != None :
            
            if i == (pos - 1) :
                
                newNode.nextRef = temp.nextRef
                temp.nextRef = newNode
                return
            else :
                temp = temp.nextRef

            i += 1
            
        return

# Main code
if __name__ == "__main__" :

    # Create a Node object
    # with given data    
    newNode = Node(10)

    # pointing head to the 
    # first node
    head = newNode

    insert(head,20,1)
    insert(head,30,2)
    insert(head,40,3)
    
    print("Linked List Before Deletion: ")
    traversal(head)

    head = deletion(30,head)
    
    print("\nLinked List After Deletion of Node with 30 data")
    traversal(head)

Output:

Linked List Before Deletion: 
10 20 30 40 
Linked List After Deletion of Node with 30 data
10 20 40 

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