-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path04_circularLL_josephus.py
126 lines (99 loc) · 2.74 KB
/
04_circularLL_josephus.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
self.head.next = self.head
cur = self.head
while cur.next != self.head:
cur = cur.next
cur.next = new_node
new_node.next = self.head
def prepend(self, data):
new_node = Node(data)
cur = self.head
new_node.next = self.head
if not self.head:
new_node.next = new_node
while cur.next != self.head:
cur = cur.next
cur.next = new_node
self.head = new_node
def remove(self, key):
if self.head.data == key:
cur = self.head
nxt = self.head.next
while cur.next != self.head:
cur = cur.next
cur.next = nxt
self.head = nxt
cur = None
else:
cur = self.head
prev = None
while cur.next != self.head:
prev = cur
cur = cur.next
if cur.data == key:
prev.next = cur.next
cur = cur.next
def remove_node(self, node):
if self.head == node:
cur = self.head
nxt = self.head.next
while cur.next != self.head:
cur = cur.next
cur.next = nxt
self.head = nxt
else:
cur = self.head
prev = None
while cur.next != self.head:
prev = cur
cur = cur.next
if cur == node:
prev.next = cur.next
cur = cur.next
def __len__(self):
cur = self.head
count = 0
while cur:
count += 1
cur = cur.next
if cur == self.head:
break
return count
def print_list(self):
cur = self.head
while cur:
print(cur.data)
cur = cur.next
if cur == self.head:
break
def josephus_circle(self, step):
cur = self.head
while len(self) > 1:
count = 1
while count != step:
cur = cur.next
count += 1
print("Removed : " + str(cur.data))
self.remove_node(cur)
cur = cur.next
cllist = CircularLinkedList()
cllist.append(1)
cllist.append(2)
cllist.append(3)
cllist.append(4)
cllist.append(5)
cllist.append(6)
cllist.print_list()
print("\n")
cllist.josephus_circle(2)
cllist.print_list()