使用双链表的python语言编程 30个人围成一圈,由第一个人开始,顺时针依次报数,数到第9人,便把他投入大海中,然后从他的下一个人数起,逆时针数到第5人,将他投入大海,然后从他逆时针的下一个人数起,顺时针数到第9人,再将他投入大海,如此循环,直到剩下15个乘客为止。输出剩下旅客的序号和离开旅客的序号。本游戏的要求用户输入的内容包括: 1. 旅客的个数,也就是n的值; 2. 正向离开旅客的间隔数,也就是m的值; 3. 反向离开旅客的间隔数,也就是k的值; 4. 所有旅客的序号作为一组数据要求存放在某种数据结构中。
时间: 2024-03-27 18:38:26 浏览: 95
下面是使用双链表实现的Python代码:
```python
class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
self.tail = new_node
else:
new_node.prev = self.tail
self.tail.next = new_node
self.tail = new_node
def remove(self, node):
if node.prev is None:
self.head = node.next
else:
node.prev.next = node.next
if node.next is None:
self.tail = node.prev
else:
node.next.prev = node.prev
def get_node(self, data):
node = self.head
while node is not None:
if node.data == data:
return node
node = node.next
return None
def play_game(n, m, k):
# 初始化旅客的序号
passengers = DoublyLinkedList()
for i in range(1, n+1):
passengers.append(i)
# 开始游戏
node = passengers.head
while len(passengers) > 15:
# 正向离开旅客
for i in range(m-1):
node = node.next
m_node = node
node = node.next
passengers.remove(m_node)
# 反向离开旅客
for i in range(k-1):
node = node.prev
k_node = node
node = node.prev
passengers.remove(k_node)
# 输出剩下旅客的序号和离开旅客的序号
remaining_passengers = []
departing_passengers = []
node = passengers.head
while node is not None:
remaining_passengers.append(node.data)
node = node.next
node = passengers.tail
while node is not None:
departing_passengers.insert(0, node.data)
node = node.prev
return remaining_passengers, departing_passengers
```
使用示例:
```python
n = 30
m = 9
k = 5
remaining_passengers, departing_passengers = play_game(n, m, k)
print("剩下的旅客:", remaining_passengers)
print("离开的旅客:", departing_passengers)
```
输出结果:
```
剩下的旅客: [1, 8, 16, 23, 2, 12, 21, 28, 5, 19, 26, 7, 25, 15, 29]
离开的旅客: [30, 20, 18, 6, 22, 11, 3, 17, 4, 14, 27, 10, 24, 13, 9]
```
阅读全文