Skip to content

Commit 7f79869

Browse files
committed
Merge remote-tracking branch 'upstream/master'
2 parents 4c410e3 + b4213a7 commit 7f79869

File tree

2 files changed

+69
-12
lines changed

2 files changed

+69
-12
lines changed
Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,46 @@
11
package com.coding.basic.queue;
22

33
public class CircleQueue <E> {
4-
5-
private final static int DEFAULT_SIZE = 10;
6-
4+
75
//用数组来保存循环队列的元素
8-
private Object[] elementData = new Object[DEFAULT_SIZE] ;
9-
6+
private Object[] elementData ;
7+
int size = 0;
108
//队头
119
private int front = 0;
1210
//队尾
1311
private int rear = 0;
1412

13+
public CircleQueue(int capacity){
14+
elementData = new Object[capacity];
15+
}
1516
public boolean isEmpty() {
16-
return false;
17+
return front == rear;
1718

1819
}
19-
20+
21+
public boolean isFull(){
22+
return size == elementData.length;
23+
}
2024
public int size() {
21-
return -1;
25+
return size;
2226
}
2327

24-
25-
2628
public void enQueue(E data) {
27-
29+
if(isFull()){
30+
throw new RuntimeException("The queue is full");
31+
}
32+
elementData[rear++] = data;
33+
size++;
2834
}
2935

3036
public E deQueue() {
31-
return null;
37+
if(isEmpty()){
38+
throw new RuntimeException("The queue is empty");
39+
}
40+
E data = (E)elementData[front];
41+
elementData[front] = null;
42+
front = (front+1) % elementData.length;
43+
size --;
44+
return data;
3245
}
3346
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.coding.basic.queue;
2+
3+
import org.junit.After;
4+
import org.junit.Assert;
5+
import org.junit.Before;
6+
import org.junit.Test;
7+
8+
9+
10+
public class CircleQueueTest {
11+
12+
@Before
13+
public void setUp() throws Exception {
14+
}
15+
16+
@After
17+
public void tearDown() throws Exception {
18+
}
19+
20+
@Test
21+
public void test() {
22+
CircleQueue<String> queue = new CircleQueue<String>(5);
23+
Assert.assertTrue(queue.isEmpty());
24+
Assert.assertFalse(queue.isFull());
25+
26+
queue.enQueue("a");
27+
queue.enQueue("b");
28+
queue.enQueue("c");
29+
queue.enQueue("d");
30+
queue.enQueue("e");
31+
32+
Assert.assertTrue(queue.isFull());
33+
Assert.assertFalse(queue.isEmpty());
34+
Assert.assertEquals(5, queue.size());
35+
36+
Assert.assertEquals("a", queue.deQueue());
37+
Assert.assertEquals("b", queue.deQueue());
38+
Assert.assertEquals("c", queue.deQueue());
39+
Assert.assertEquals("d", queue.deQueue());
40+
Assert.assertEquals("e", queue.deQueue());
41+
42+
}
43+
44+
}

0 commit comments

Comments
 (0)