tonglin0325的个人主页

Java数据结构——队列

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
58
59
60
61
62
63
64
65
66
67
68
69
class Queue{
private int maxSize; //队列的长度
private long[] queueArray; //创建队列的数组的引用
private int front; //创建队头的引用
private int rear; //创建队尾的引用
private int curNum; //创建当前元素的个数

public Queue(int s) { //构造函数
this.maxSize = s;
queueArray = new long[maxSize]; //创建对象
front = 0; //队头等于0
rear = -1; //队尾等于-1
curNum = 0; //当前的元素的个数是0
}

public void insert(long j){
if(rear == maxSize-1){ //如果队尾是队列的最大值-1,则队尾等于-1
rear = -1;
}
queueArray[++rear] = j; //先自加为0,然后给队尾的元素赋值
curNum++; //当前的元素的个数加1
}

public long remove(){
long temp = queueArray[front++]; //取得队头的元素,然后自加
if(front == maxSize){
front =0;
}
curNum--; //当前的元素的个数减1
return temp;
}

public long peekFront(){
return queueArray[front];
}

public boolean isEmpty(){
return (curNum==0);
}

public boolean isFull(){
return (curNum==maxSize);
}

public int Size(){ //返回当前队列元素的个数
return curNum;
}

}

public class Queue_demo {

public static void main(String[] args) {
// TODO 自动生成的方法存根
Queue queue_demo = new Queue(5);
queue_demo.insert(50);
queue_demo.insert(60);
queue_demo.insert(70);
queue_demo.insert(80);
queue_demo.remove();
queue_demo.insert(50);

while( !queue_demo.isEmpty()){
long value = queue_demo.remove();
System.out.print(value+"、");
}
}
}