Creating Linked LIst

Why you need to create your linked list if Python has its own Linked List. The answer is for clear understanding of the data structure and to prepare for job interview.

Create a Linked List:

First, Create a class that represent node of the linked list:

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

This represents each Node of the list : data and Next pointer.

Then, Create a class that represent Linked list:

class LinkedList:
    def __init__(self):
        self.head = None

This represents the linked list which has a head pointer which usually points to the first element of the list or None if the list is empty.

Now you can write an append function inside Linked List class to add data into Linked List like:

def append(self, element):
    newNode = Node(element)
    if self.head is None:
        self.head = newNode
    else:
        current = self.head
        while current.next:
            current = current.next
        current.next = newNode

What is happening with the above code: Lets Analyse the code. Or how do you think?

We have an element to insert. Here when an element is passed to insert, a node is created with that element first. 

Then, we check if the head is None. What does this means? If the head is None, then there is no element in the list. 

If there is no element in the list, this is our first element. Whenever we insert the first element, we need to point head to the node. This is what the if loop does.

Now, the else part defines the steps to be executed if the list is not empty. If the list is not empty, you have to go to the last node in the list. How do you identify if the node is the last node? If the node is the last node, the next pointer will be None which means no more elements are in the list. Lets see how we can reach the last node. 

current = self.head

We are taking the head value and assigning it to a variable called 'current'. We know head means the first node. Now, we need to check if the next of the current node has a value. If not, we can stop traversing . Otherwise, assign the next node to the variable 'current' and repeat the process until the next is None. 

Finally, we insert the Node with the element to the current.next.

Now to create a linked list, you can use the below code:

lt = LinkedList()
mylt=[1,2,3,4,5,6,6]
for i in mylt:
    lt.append(i)

(or) You can directly write the code inside __init__() to create linked list using a single call by just iterating the list(Try IT!!!)

Try here>>>