forked from BinaryBall/java-base
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularQueue.java
More file actions
57 lines (48 loc) · 1.29 KB
/
CircularQueue.java
File metadata and controls
57 lines (48 loc) · 1.29 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
48
49
50
51
52
53
54
55
56
57
package com.jamal;
/**
* 环形队列,不需要数据迁移,提高性能
*/
public class CircularQueue {
// 存放数据的数组
private String[] items;
// 容器的大小
private int size = 0;
// 第一个节点
private int head = 0;
// 最后一个节点
private int tail = 0;
// 构造函数
public CircularQueue(int size){
this.size = size;
items = new String[size];
}
/**
* 入队操作
* @param data
* @return
*/
public int enqueue(String data){
// 如果最后一个节点等于容器大小,说明队列满了
/**
* 判断环形队列满了的条件,(tail+1)求余等于head
*/
if ((tail+1)%size == head) return -1;
// 向队列中添加元素
items[tail] = data;
// 因为是环形队列,所以下边是数组长度的余数
tail= (tail+1)%size;
return 1;
}
/**
* 出队操作
* @return
*/
public String dequeue(){
// 第一个元素和最后一个元素相等时,队列为空
if (head == tail) return null;
String result = items[head];
// 因为是环形队列,所以下边是数组长度的余数
head = (head+1)% size ;
return result;
}
}