Linked List Implementation in Python

In this class, we do Linked List Implementation in Python.

For Complete YouTube Video: Click Here

Linked List

The reader should have a prior understanding of data structures. Check our data structures course.

For better understanding, check the stack implementation in python. Click here.

First, refresh the concept of a linked list. Then we give an intuition on implementing linked list node insertion at last.

Continue implementing remaining operations with this understanding.

In a linked list, each node, we have data and link variables.

Variable data is used to save the element, and the variable link is used to save the address of the next node.

To create a node in python, we create a class as shown below.

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

When we create an object to the above class node, the object will assign a space for data and link.

We use the class Node in the linked list class to create a Node.

We use a variable head to point to the first node in the list.

The first node will contain the address of the second node in the list. So on.

The last node contains None in the variable link.

The implementation of the linked list insertion operation is given in the program below.

Analyze the code for better practice.

Program

class Node:
    def __init__(self,data):
        self.data=data
        self.link=None
class linkedlist:
    def __init__(self):
        self.head=None
    def insert(self,element):
        ob=Node(element)
        if self.head==None:
            self.head=ob
        else:
            x=self.head
            while(x.link!=None):
                x=x.link
            x.link=ob
            print("element inserted at the end")
    def display(self):
        x=self.head
        while x.link!=None:
            print(x.data)
            x=x.link
        print(x.data)
obj=linkedlist()
obj.insert(10)
obj.insert(20)
obj.insert(30)
obj.display()

The loop in the above program taking the head node address and moving to the end of the list.

The condition to move to the end of the list x.link==None. Update x to the next node.

Attach the new node at the end of the list.

The new node is created by defining the object to the class node.