File tree 2 files changed +69
-12
lines changed
liuxin/data-structure/answer/src/com/coding/basic/queue 2 files changed +69
-12
lines changed Original file line number Diff line number Diff line change 1
1
package com .coding .basic .queue ;
2
2
3
3
public class CircleQueue <E > {
4
-
5
- private final static int DEFAULT_SIZE = 10 ;
6
-
4
+
7
5
//用数组来保存循环队列的元素
8
- private Object [] elementData = new Object [ DEFAULT_SIZE ] ;
9
-
6
+ private Object [] elementData ;
7
+ int size = 0 ;
10
8
//队头
11
9
private int front = 0 ;
12
10
//队尾
13
11
private int rear = 0 ;
14
12
13
+ public CircleQueue (int capacity ){
14
+ elementData = new Object [capacity ];
15
+ }
15
16
public boolean isEmpty () {
16
- return false ;
17
+ return front == rear ;
17
18
18
19
}
19
-
20
+
21
+ public boolean isFull (){
22
+ return size == elementData .length ;
23
+ }
20
24
public int size () {
21
- return - 1 ;
25
+ return size ;
22
26
}
23
27
24
-
25
-
26
28
public void enQueue (E data ) {
27
-
29
+ if (isFull ()){
30
+ throw new RuntimeException ("The queue is full" );
31
+ }
32
+ elementData [rear ++] = data ;
33
+ size ++;
28
34
}
29
35
30
36
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 ;
32
45
}
33
46
}
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments