forked from geekcomputers/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSplit_Circular_Linked_List.py
67 lines (59 loc) · 1.83 KB
/
Split_Circular_Linked_List.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Circular_Linked_List:
def __init__(self):
self.head = None
def Push(self, data):
temp = Node(data)
temp.next = self.head
temp1 = self.head
if self.head is not None:
while temp1.next is not None:
temp1 = temp1.next
temp1.next = temp
else:
temp.next = temp
self.head = temp
def Split_List(self, head1, head2):
if self.head is None:
return
slow_ptr = self.head
fast_ptr = self.head
while fast_ptr.next != self.head and fast_ptr.next.next != self.head:
fast_ptr = fast_ptr.next.next
slow_ptr = slow_ptr.next.next
if fast_ptr.next.next == self.head:
fast_ptr = fast_ptr.next
head1 = self.head
slow_ptr.next = head1
if self.head.next != self.head:
head2.head = slow_ptr.next
fast_ptr.next = slow_ptr.next
def Display(self):
temp = self.head
if self.head is not None:
while temp:
print(temp.data, "->", end=" ")
temp = temp.next
if temp == self.head:
print(temp.data)
break
if __name__ == "__main__":
L_list = Circular_Linked_List()
head1 = Circular_Linked_List()
head2 = Circular_Linked_List()
L_list.Push(6)
L_list.Push(4)
L_list.Push(2)
L_list.Push(8)
L_list.Push(12)
L_list.Push(10)
L_list.Split_List(head1, head2)
print("Circular Linked List: ")
L_list.Display()
print("Firts Split Linked List: ")
head1.Display()
print("Second Split Linked List: ")
head2.Display()