用循环链表解决瑟夫环问题python并有一个完整的主程序运行
时间: 2024-02-26 14:57:35 浏览: 29
好的,以下是用循环链表解决瑟夫环问题的 Python 代码:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class JosephusCircle:
def __init__(self, n, m):
self.head = None
self.tail = None
self.n = n
self.m = m
self.populate()
def populate(self):
for i in range(self.n):
self.add(i+1)
def add(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
self.tail = new_node
new_node.next = self.head
else:
self.tail.next = new_node
self.tail = new_node
self.tail.next = self.head
def remove(self, node):
if self.n == 1:
self.head = None
self.tail = None
elif node == self.head:
self.head = self.head.next
self.tail.next = self.head
elif node == self.tail:
current = self.head
while current.next != self.tail:
current = current.next
current.next = self.head
self.tail = current
else:
current = self.head
while current.next != node:
current = current.next
current.next = node.next
self.n -= 1
def get_winner(self):
current = self.head
while self.n > 1:
for i in range(self.m-1):
current = current.next
self.remove(current)
current = current.next
return self.head.data
if __name__ == "__main__":
n = int(input("请输入总人数n:"))
m = int(input("请输入报数m:"))
circle = JosephusCircle(n, m)
print("瑟夫环问题的解为:", circle.get_winner())
```
运行这段代码,你会看到一个提示输入总人数和报数的界面,输入相应的数字后,它会输出瑟夫环问题的解。