数据结构循环队列代码舞会配对
时间: 2023-11-28 16:43:32 浏览: 66
数据结构课程设计舞伴配对程序
以下是利用Python实现循环队列模拟舞伴配对问题的代码:
```python
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
def dance_partner(male_dancers, female_dancers):
male_queue = Queue()
female_queue = Queue()
for male_dancer in male_dancers:
male_queue.enqueue(male_dancer)
for female_dancer in female_dancers:
female_queue.enqueue(female_dancer)
while not male_queue.is_empty() and not female_queue.is_empty():
print("Male dancer is:", male_queue.dequeue(), "and female dancer is:", female_queue.dequeue())
if not male_queue.is_empty():
print("Unmatched male dancers are:", end=" ")
while not male_queue.is_empty():
print(male_queue.dequeue(), end=" ")
print()
if not female_queue.is_empty():
print("Unmatched female dancers are:", end=" ")
while not female_queue.is_empty():
print(female_queue.dequeue(), end=" ")
print()
male_dancers = ['Tom', 'Jerry', 'Mike']
female_dancers = ['Lucy', 'Lily', 'Mary']
dance_partner(male_dancers, female_dancers)
```
运行结果如下:
```
Male dancer is: Tom and female dancer is: Lucy
Male dancer is: Jerry and female dancer is: Lily
Male dancer is: Mike and female dancer is: Mary
```
阅读全文