java实现循环队列模拟舞伴配对
时间: 2023-05-18 14:05:44 浏览: 177
利用循环队列模拟舞伴配对问题
以下是Java实现循环队列模拟舞伴配对的代码:
```java
public class DancePartnerQueue {
private int maxSize;
private char[] queueArray;
private int front;
private int rear;
public DancePartnerQueue(int size) {
maxSize = size + 1;
queueArray = new char[maxSize];
front = 0;
rear = -1;
}
public void insert(char c) {
if (rear == maxSize - 1) {
rear = -1;
}
queueArray[++rear] = c;
}
public char remove() {
char temp = queueArray[front++];
if (front == maxSize) {
front = 0;
}
return temp;
}
public boolean isEmpty() {
return (rear + 1 == front || front + maxSize - 1 == rear);
}
public boolean isFull() {
return (rear + 2 == front || front + maxSize - 2 == rear);
}
public void display() {
System.out.print("Queue (front-->rear): ");
if (!isEmpty()) {
if (front <= rear) {
for (int i = front; i <= rear; i++) {
System.out.print(queueArray[i] + " ");
}
} else {
for (int i = front; i < maxSize; i++) {
System.out.print(queueArray[i] + " ");
}
for (int i = 0; i <= rear; i++) {
System.out.print(queueArray[i] + " ");
}
}
}
System.out.println();
}
public void dancePartner() {
DancePartnerQueue maleQueue = new DancePartnerQueue(maxSize);
DancePartnerQueue femaleQueue = new DancePartnerQueue(maxSize);
for (int i = 0; i < maxSize - 1; i++) {
char c = (char) (Math.random() * 2 == 0 ? 'M' : 'F');
if (c == 'M') {
maleQueue.insert(c);
} else {
femaleQueue.insert(c);
}
}
while (!maleQueue.isEmpty() && !femaleQueue.isEmpty()) {
System.out.println("The dance partners are: " + maleQueue.remove() + " and " + femaleQueue.remove());
}
if (!maleQueue.isEmpty()) {
System.out.println("There are " + (rear - front + 1) + " male dancers waiting to dance.");
}
if (!femaleQueue.isEmpty()) {
System.out.println("There are " + (rear - front + 1) + " female dancers waiting to dance.");
}
}
public static void main(String[] args) {
DancePartnerQueue queue = new DancePartnerQueue(10);
queue.dancePartner();
}
}
```
在这个代码中,我们首先定义了一个循环队列类`DancePartnerQueue`,它包含了队列的基本操作,如插入、删除、判断队列是否为空或已满等。然后我们在`dancePartner()`方法中,创建了两个循环队列`maleQueue`和`femaleQueue`,并随机生成男女舞者,将他们分别插入到对应的队列中。接着我们使用一个循环,不断从男女队列中取出一个男舞者和一个女舞者,输出他们的配对信息,直到其中一个队列为空。最后,如果还有男舞者或女舞者在队列中等待,我们也会输出相应的信息。
在`main()`方法中,我们创建了一个队列对象,并调用了`dancePartner()`方法,模拟了舞伴配对的过程。
阅读全文