8
Create a Simple Linked List Using Python
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
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
In order to create a linked list, we need to create an object from the LinkedList class.
LL = LinkedList()
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)
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
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
We have to call the printList() method in order to print the linked list.
LL.printList()
This is how the output will look:
10
11
12
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()
References:
8