DEV Community

Cover image for Create a Simple Linked List Using Python
Abu Hurayra
Abu Hurayra

Posted on • Updated on

Create a Simple Linked List Using Python

Step 1: Create a Node Class

Every linked list has nodes that are linked together to form a linked list. A node contains a data and a link. The link is used to store the address of the next element in the list.

Let's create a Node class in python:

class Node:
    def __init__(self, data):
        self.data = data 
        self.next = None
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a Linked List Class

A linked list class will contain the head of the linked lists and other methods like insert, delete and search.

Let's create a LinkedList class in python:

class LinkedList:
    def __init__(self):
        self.head = None
Enter fullscreen mode Exit fullscreen mode

Step 3: Create a Linked List

In order to create a linked list, we need to create an object from the LinkedList class.

LL = LinkedList()
Enter fullscreen mode Exit fullscreen mode

Now let's create 3 nodes with values 10, 11 and 12. The first node is the head.

LL.head = Node(10)
second = Node(11)
third = Node(12)
Enter fullscreen mode Exit fullscreen mode

Link all the nodes together: head will point to second and second will point to third. The third node points to None which is already set.

LL.head.next = second
second.next = third
Enter fullscreen mode Exit fullscreen mode

Step 4: Create a Method to Print the list

Let's add a printList() method to the LinkedList class. This method will take the head node and print the values while traversing the node until it reaches the end.

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

    def printList(self):
        temp = self.head
        while temp:
            print(temp.data)
            temp = temp.next
Enter fullscreen mode Exit fullscreen mode

We have to call the printList() method in order to print the linked list.

LL.printList()
Enter fullscreen mode Exit fullscreen mode

This is how the output will look:

10
11
12
Enter fullscreen mode Exit fullscreen mode

The complete python program:

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

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

    def printList(self):
        temp = self.head
        while temp:
            print(temp.data)
            temp = temp.next


LL = LinkedList()

LL.head = Node(1)
second = Node(2)
third = Node(3)

LL.head.next = second
second.next = third

LL.printList()
Enter fullscreen mode Exit fullscreen mode

Thanks for reading the post 😄


References:

  1. https://www.geeksforgeeks.org/linked-list-set-1-introduction/

Oldest comments (0)