File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * An implementation of queue using a static array.
3+ *
4+ * <p>
5+ * Operations and their time complexities are:
6+ * <ul>
7+ * <li><code>enqueue</code>: O(1)</li>
8+ * <li><code>dequeue</code>: O(n)</li>
9+ * <li><code>peek</code>: O(1)</li>
10+ * </ul>
11+ */
12+ public class ArrayQueue <T > {
13+ private Object [] array ;
14+ private int length ;
15+
16+ public ArrayQueue (int maxLength ) {
17+ this .array = new Object [maxLength ];
18+ this .length = 0 ;
19+ }
20+
21+ public ArrayQueue <T > enqueue (T data ) {
22+ if (this .length == this .array .length )
23+ return this ;
24+
25+ this .array [this .length ++] = data ;
26+ return this ;
27+ }
28+
29+ public ArrayQueue <T > dequeue () {
30+ if (this .length == 0 )
31+ return this ;
32+
33+ int i ;
34+ for (i = 1 ; i < this .length ; i ++)
35+ this .array [i - 1 ] = this .array [i ];
36+
37+ this .array [i - 1 ] = null ;
38+ this .length --;
39+ return this ;
40+ }
41+
42+ @ SuppressWarnings ("unchecked" )
43+ public T peek () {
44+ return (T ) this .array [0 ];
45+ }
46+
47+ public static void main (String [] args ) {
48+ ArrayQueue <Integer > queue = new ArrayQueue <Integer >(10 );
49+
50+ for (int i = 0 ; i < 15 ; i ++)
51+ queue .enqueue (i );
52+
53+ for (int i = 0 ; i < 20 ; i ++) {
54+ System .out .println (queue .peek ());
55+ queue .dequeue ();
56+ }
57+ }
58+ }
You can’t perform that action at this time.
0 commit comments