josephus问题链表
时间: 2024-02-02 20:04:49 浏览: 70
约瑟夫问题_链表
以下是使用链表解决Josephus问题的Python代码:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
def add_node(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
new_node.next = self.head
else:
current = self.head
while current.next != self.head:
current = current.next
current.next = new_node
new_node.next = self.head
def remove_node(self, node):
if self.head == node:
current = self.head
while current.next != self.head:
current = current.next
current.next = self.head.next
self.head = self.head.next
else:
current = self.head
prev = None
while current.next != self.head:
prev = current
current = current.next
if current == node:
prev.next = current.next
break
def get_survivor(self, step):
current = self.head
while len(self) > 1:
for i in range(step - 1):
current = current.next
self.remove_node(current)
current = current.next
return self.head.data
def __len__(self):
current = self.head
count = 0
while current:
count += 1
current = current.next
if current == self.head:
break
return count
# 示例
cll = CircularLinkedList()
for i in range(1, 41):
cll.add_node(i)
print(cll.get_survivor(3)) # 输出:4
```
阅读全文