用循环链表编约瑟夫环问题python并实现一个完整的主程序运行
时间: 2024-02-26 20:57:33 浏览: 86
好的,以下是用循环链表编写约瑟夫环问题的 Python 代码:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class JosephusCircle:
def __init__(self, n, k):
self.head = None
self.tail = None
self.n = n
self.k = k
self.size = 0
self.populate()
def populate(self):
for i in range(1, self.n+1):
self.add(i)
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
self.size += 1
def remove(self, node):
if self.size == 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.size -= 1
def get_winner(self):
current = self.head
while self.size > 1:
for i in range(self.k - 1):
current = current.next
self.remove(current)
current = current.next
return self.head.data
if __name__ == "__main__":
n = int(input("请输入总人数n:"))
k = int(input("请输入报数k:"))
circle = JosephusCircle(n, k)
print("约瑟夫环问题的解为:", circle.get_winner())
```
运行这段代码,你会看到一个提示输入总人数和报数的界面,输入相应的数字后,它会输出约瑟夫环问题的解。
阅读全文