# Python program to check that two circular
# linked list are identical or not
# Circular linked list node class
class Node:
def __init__(self, data):
self.data = data
self.next = None
# function to insert a node in
# tail in circular linked list
def insertNode(head, tail, d):
# first insertion in circular
# linked list
if(head is None):
newNode = Node(d)
head = newNode
tail = newNode
newNode.next = newNode
else:
# non-empty list
temp = Node(d)
temp.next = tail.next
tail.next = temp
tail = tail.next
return head, tail
# function to print circular linked list
def printList(head):
curr = head
# if circular linked list is empty
if(head is None):
print("List is Empty.")
return
# else iterate until node is not head
while True:
print(curr.data, end=" ")
curr = curr.next
if(curr == head):
break
print("")
def convertString(head):
curr = head
s = ""
# if circular linked list is empty
if(head is None):
return ""
# else iterate until node is not head
while True:
s += str(curr.data)
s += "*"
curr = curr.next
if(curr == head):
break
return s
# function to check that two circular
# linked list are identical or not
def checkIdentical(S, T):
# check if sizes of two strings are same
if(len(S) != len(T)):
return False
temp = S+S
if T in temp:
return True
else:
return False
# driver program
head1 = None
tail1 = None
head1, tail1 = insertNode(head1, tail1, 1)
head1, tail1 = insertNode(head1, tail1, 2)
head1, tail1 = insertNode(head1, tail1, 3)
head1, tail1 = insertNode(head1, tail1, 4)
head1, tail1 = insertNode(head1, tail1, 5)
head1, tail1 = insertNode(head1, tail1, 1)
head1, tail1 = insertNode(head1, tail1, 2)
head1, tail1 = insertNode(head1, tail1, 6)
head2 = None
tail2 = None
head2, tail2 = insertNode(head2, tail2, 5)
head2, tail2 = insertNode(head2, tail2, 1)
head2, tail2 = insertNode(head2, tail2, 2)
head2, tail2 = insertNode(head2, tail2, 6)
head2, tail2 = insertNode(head2, tail2, 1)
head2, tail2 = insertNode(head2, tail2, 2)
head2, tail2 = insertNode(head2, tail2, 3)
head2, tail2 = insertNode(head2, tail2, 4)
print("First circular linked list : ")
printList(head1)
print("Second Circular linked list : ")
printList(head2)
S = convertString(head1)
T = convertString(head2)
flag = checkIdentical(S, T)
if(flag):
print("Identical")
else:
print("Not Identical")
# This code is contributed by Kirti Agarwal(kirtiagarwal23121999)