Python Linked List đ
Linked List
A linked list is a sequence of data elements, which are connected together via links. Each data element contains a connection to another data element in form of a pointer. Python does not have linked lists in its standard library. We implement the concept of linked lists using the concept of nodes.
⨠Creating a Linked List
We create a Node class to hold the data and a reference to the next node.
python
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.nextval = None
class SLinkedList:
def __init__(self):
self.headval = None
list1 = SLinkedList()
list1.headval = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")
# Link first Node to second node
list1.headval.nextval = e2
# Link second Node to third node
e2.nextval = e3đŽ Interactive Linked List Demo
âšī¸ Ready to link nodes!
Mon
Node 0
HEAD
Tue
Node 1
Wed
Node 2
â None
đļ Traversing a Linked List
Singly linked lists can be traversed in only forward direction starting form the first data element.
python
class SLinkedList:
def __init__(self):
self.headval = None
def listprint(self):
printval = self.headval
while printval is not None:
print (printval.dataval)
printval = printval.nextval
list1 = SLinkedList()
list1.headval = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")
list1.headval.nextval = e2
e2.nextval = e3
list1.listprint()đĄ Did You Know?
Linked lists are dynamic data structures, meaning they can grow and shrink at runtime.