Linked List creation In "Python"

Photo by JJ Ying on Unsplash

Linked List creation In "Python"

We can create linked list easily in 2 possible ways

  1. Using direct object linking

  2. Using insert method

Direct object linking

Linkedlist node is the combination of value as well as next node address

class LinkedList:
    def __init__(self, value):
        self.value = value
        self.next = None
node1 = LinkedList(1) #1->None
node2 = LinkedList(2) #2->None
node3 = LinkedList(3) #3->None

node1.next = node2 #1->2->None
node2.next = node3 #1->2->3->None

current_node = node1 #pointing the current node with this variable

while current_node:
    print(current_node.value,'->', end="")
    if current_node.next is None:
        print('None')
        breaak
    current_node = current_node.next

Output: 
1->2->3->None

The above example explains

  1. First we created each node individually

  2. To make connection between the nodes we attached each node next attribute to the next node.

  3. In the previous step only we created the linked list

  4. To print the linkedlist in the console we have to traverse through the linkedlist

  5. First assigned the first node to the current_node variable

  6. After printing the current_node value we assigned the this variable to the next node

Using insert method

class LinkedList:
    def __init__(self, value):
        self.value = value
        self.next = None
class LL:
    def __init__(self, head):
        self.head = None
    def insert(self, value):
        node = LinkedList(value)
        if self.head is None:
            self.head = node
            return
        current = self.head
        while current:
            print(current.value, '->', end="")
            if current.next is None:
                curren.next = node
                break
            current = current.next
    def printLL(self):
        current = self.head
        while current:
            print(current.value, '->', end="")
            current = current.next
        print('None')

LL_obj = LL()
LL_obj.insert(1)
LL_obj.print()

Output:
1->None

Here the creation a bit tricky

  1. After immediately calling the class we are assigning out head value to the None

  2. With the help of insert method weather we create out first linkedlist node or insert the value to the existing linkedlist.

  3. If it is our first value we just create out first node will return from there

  4. if we are trying to add some values to the existing linkedlist then first we will assign our head value to the currrent_node.

  5. After we have to traverse through the entire linkedlist until we meet the condition where out current.next is None because this is where we have to add our node.

  6. here I defined another method called printLL in order to print the linkedlist.

Did you find this article valuable?

Support Malavi Pande by becoming a sponsor. Any amount is appreciated!