Linked List :
Linked List is also a Linear Data structure.
The main difference between List and Linked lists is the way that they store elements in memory. lists use a contiguous memory block to store references to their data, whereas linked lists store references as part of their own elements.
Linked List Concepts :
Each element of a linked list is called a node, and every node has two different fields:
- Data : It holds the value of the node.
- Next : it holds the address of the next node.
Linked List is a collection of nodes, where head points to the first node of the linked list and the last node of the linked list points to None.
# Creating Node Class :
class Node:
def __init__(self, data, next = None):
self.data = data
self.next = next
# Creating LinkedList Class :
class LinkedList:
def __init__(self):
self.head = None
def __repr__(self):
node = self.head
nodes = []
while node is not None:
nodes.append(node.data)
node = node.next
nodes.append("None")
return " -> ".join(nodes)
# Creating Instance of LinkedList :
llist = LinkedList()
fNode = Node('a')
sNode = Node('b')
tNode = Node('c')
llist.head = fNode
fNode.next = sNode
sNode.next = tNode
tNode.next= Node('d')
print(type(llist))
print(llist)
# Output :
< class '__main__.LinkedList' >
a -> b -> c -> d -> None