用 java语言以测试驱动开发实现循环队列
时间: 2023-11-18 07:00:48 浏览: 64
以下是用 Java 语言实现循环队列的示例代码,采用测试驱动开发方式:
```java
import org.junit.Test;
import static org.junit.Assert.*;
public class CircularQueueTest {
@Test
public void testEnqueueAndDequeue() {
CircularQueue queue = new CircularQueue(3);
assertTrue(queue.isEmpty());
assertFalse(queue.isFull());
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
assertTrue(queue.isFull());
assertFalse(queue.isEmpty());
assertEquals(1, queue.dequeue());
assertEquals(2, queue.dequeue());
assertEquals(3, queue.dequeue());
assertTrue(queue.isEmpty());
assertFalse(queue.isFull());
}
@Test
public void testEnqueueAndDequeueWithWrapAround() {
CircularQueue queue = new CircularQueue(3);
assertTrue(queue.isEmpty());
assertFalse(queue.isFull());
queue.enqueue(1);
queue.enqueue(2);
assertEquals(1, queue.dequeue());
queue.enqueue(3);
assertTrue(queue.isFull());
assertFalse(queue.isEmpty());
assertEquals(2, queue.dequeue());
assertEquals(3, queue.dequeue());
assertTrue(queue.isEmpty());
assertFalse(queue.isFull());
}
@Test
public void testEnqueueAndDequeueWithOverwrite() {
CircularQueue queue = new CircularQueue(3);
assertTrue(queue.isEmpty());
assertFalse(queue.isFull());
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
assertTrue(queue.isFull());
assertFalse(queue.isEmpty());
assertEquals(2, queue.dequeue());
assertEquals(3, queue.dequeue());
assertEquals(4, queue.dequeue());
assertTrue(queue.isEmpty());
assertFalse(queue.isFull());
}
}
class CircularQueue {
private int[] buffer;
private int front;
private int rear;
private int size;
public CircularQueue(int capacity) {
buffer = new int[capacity];
front = 0;
rear = 0;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == buffer.length;
}
public void enqueue(int value) {
if (isFull()) {
dequeue();
}
buffer[rear] = value;
rear = (rear + 1) % buffer.length;
size++;
}
public int dequeue() {
if (isEmpty()) {
throw new RuntimeException("Queue is empty");
}
int value = buffer[front];
front = (front + 1) % buffer.length;
size--;
return value;
}
}
```
上述代码中,CircularQueue 类实现了循环队列的基本操作。在测试方法中,使用 JUnit 进行测试,确保循环队列的实现正确,并覆盖了各种情况,包括正常情况、环绕情况和覆盖情况。
阅读全文