1
+ class Node :
2
+ def __init__ (self , value = None , nextNode = None , prevNode = None ):
3
+ self .value = value
4
+ self .nextNode = nextNode
5
+ self .prevNode = prevNode
6
+
7
+ def get_next_node (self ):
8
+ return self .nextNode
9
+
10
+ def get_prev_node (self ):
11
+ return self .prevNode
12
+
13
+ def get_node_val (self ):
14
+ return self .value
15
+
16
+ class CircularLinkedList :
17
+ def __init__ (self ):
18
+ self .head = None
19
+ self .tail = None
20
+ self .chain_len = 0
21
+
22
+ def add_node_to_chain (self , value = None , Front = False ):
23
+ new_node = Node (value = value )
24
+ if Front :
25
+ self .head .prevNode = new_node
26
+ new_node .nextNode = self .head
27
+ self .head = new_node
28
+ # To make the linked_list circular, chain's head & tail should be connected
29
+ self .head .prevNode = self .tail
30
+ self .tail .nextNode = self .head
31
+ else :
32
+ if self .head is None :
33
+ self .head = new_node
34
+ self .tail = self .head
35
+ else :
36
+ self .tail .nextNode = new_node
37
+ new_node .prevNode = self .tail
38
+ self .tail = new_node
39
+ self .tail .nextNode = self .head
40
+ self .chain_len += 1
41
+
42
+ def get_head_node (self ):
43
+ return self .head
44
+
45
+ def get_tail_node (self ):
46
+ return self .tail
47
+
48
+ def get_chain_length (self ):
49
+ return self .chain_len
50
+
51
+ def print_chain (self , circular = False ):
52
+ head = self .head
53
+ repeat = 0
54
+ while head :
55
+ print (' ' ,head .get_node_val (), "->" , end = '' )
56
+ if head is self .get_tail_node ():
57
+ if not repeat :
58
+ repeat += 1
59
+ else :
60
+ print ("end_of_repetition" )
61
+ break
62
+ head = head .get_next_node ()
63
+ else :
64
+ print (' chain_end' )
65
+
66
+ if __name__ == '__main__' :
67
+ my_dl_list = CircularLinkedList ()
68
+
69
+ my_dl_list .add_node_to_chain (1 )
70
+ my_dl_list .add_node_to_chain (2 )
71
+ my_dl_list .add_node_to_chain (3 )
72
+ my_dl_list .add_node_to_chain (4 )
73
+
74
+ print (f"Length of chain -> { my_dl_list .get_chain_length ()} " )
75
+
76
+ my_dl_list .print_chain ()
77
+
78
+ print ('-- Now adding a node to the front of the chain --' )
79
+
80
+ my_dl_list .add_node_to_chain (5 , Front = True )
81
+
82
+ my_dl_list .print_chain ()
0 commit comments