Data structures in Python, Series 2 : Circular Linked List
Insertion in Circular Linked List :
class node():
def __init__(self, data, Next = None):
self.next = Next
self.data = data
class circlist():
def __init__(self):
self.head = None
self.next = None
self.data = 0
def add_node(self,data):
if self.head == None:
self.head = node(data)
self.head.next = self.head
else:
b = self.head
a = node(data,self.head)
while b.next != self.head :
b = b.next
b.next = a
def printl(self):
a = self.head
while a.next != self.head:
print(f'{a.data}',end= '>>')
a = a.next
print(f'{a.data}',end= '>>')
print(f'{self.head.data}')
if __name__ == '__main__':
lis = circlist()
lis.add_node(2)
lis.add_node(3)
lis.add_node(5)
lis.printl()
Circular linked list is a sequence of elements in which every element has link to its next element in the sequence and the last element has a link to the first element in the sequence.
Insertion
In a circular linked list, the insertion operation can be performed in three ways. They are as follows...
1. Inserting At Beginning of the list
2. Inserting At End of the list
3. Inserting At Specific location in the list
Inserting At Beginning of the list
We can use the following steps to insert a new node at beginning of the circular linked list...
Step 1: Create a newNode with given value.
Step 2: Check whether list is Empty (head == NULL)
Step 3: If it is Empty then, set head = newNode and newNode→next = head .
Step 4: If it is Not Empty then, define a Node pointer 'temp' and initialize with 'head'.
Step 5: Keep moving the 'temp' to its next node until it reaches to the last node (until 'temp →
next == head').
Step 6: Set 'newNode → next =head', 'head = newNode' and 'temp → next = head'.
class node():
def __init__(self, data, Next = None):
self.next = Next
self.data = data
class circlist():
def __init__(self):
self.head = None
self.next = None
self.data = 0
def add_node(self,data):
if self.head == None:
self.head = node(data)
self.head.next = self.head
else:
b = self.head
a = node(data,self.head)
while b.next != self.head :
b = b.next
b.next = a
def printl(self):
a = self.head
while a.next != self.head:
print(f'{a.data}',end= '>>')
a = a.next
print(f'{a.data}',end= '>>')
print(f'{self.head.data}')
if __name__ == '__main__':
lis = circlist()
lis.add_node(2)
lis.add_node(3)
lis.add_node(5)
lis.printl()
Comments
Post a Comment