-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyQueue.java
More file actions
47 lines (40 loc) · 1.17 KB
/
Copy pathMyQueue.java
File metadata and controls
47 lines (40 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package basic.basic_structure;
/**
* Created by sunbo_000 on 2/11/2016.
*/
public class MyQueue {
Object[] queue;
Integer max;
Integer head;
Integer tail;
public MyQueue(Integer size) {
this.queue = new Object[size];
this.max = size;
this.head = 0;
this.tail = 0;
}
public static void main(String[] args) throws Exception {
MyQueue myQueue = new MyQueue(3);
myQueue.enqueue(1);
myQueue.enqueue(2);
myQueue.enqueue(3);
System.out.println(myQueue.dequeue());
myQueue.enqueue(4);
System.out.println(myQueue.dequeue());
System.out.println(myQueue.dequeue());
System.out.println(myQueue.dequeue());
System.out.println(myQueue.dequeue());
String a = null;
}
public void enqueue(Object o) throws Exception {
if (head - tail >= max) throw new Exception("the Queue is full");
queue[head % max] = o;
head++;
}
public Object dequeue() throws Exception {
if (head - tail <= 0) throw new Exception("the Queue is empty");
Object ele = queue[tail % max];
tail++;
return ele;
}
}