队列Queue,先进先出 First In First Out (FIFO) 的线性表, 只允许在表的一端插入元素(队尾Rear), 表的另一端删除元素(队首Front),基本操作有初始化队列,判断空,入队,出队,读取队首元素。

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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
* 单个节点
*
* @author Lison-Liou
*
*/
public class Node<E> {
E data = null;
Node<E> next;

public Node() {
}

public Node(E data) {
this.data = data;
}

public Node(E data, Node<E> next) {
this.data = data;
this.next = next;
}
}
/**
* 链表队列实现
* @author Lison-Liou
*
* @param <E>
*/
public class MyQueue<E> {

int size;
Node<E> front, rear;

public void initQueue() {
front = rear = null;
}

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

public void enQueue(int data) {

if (isEmpty()) {
front = new Node(data);
rear = front;
} else {
Node newRear = new Node(data);
rear.next = newRear;
rear = newRear;
}

size++;
}

public E deQueue() {

if (!isEmpty()) {

Node<E> f0 = front;
Node<E> f = f0.next;
front = f;

size--;
return f0.data;
}
return null;
}

public E frontQueue() {
return front.data;
}

public void clear() {
while (!isEmpty()) {
deQueue();
}
}
}
//// 链表队列测试代码==========================================================================

MyQueue<Integer> queue = new MyQueue<Integer>();
queue.initQueue();

System.out.println("入队列操作--------------------------");
for (int i = 0; i < 7; i++) {
int d = random.nextInt(i + 1);
System.out.print(d + "\t");
queue.enQueue(d);
}

// System.out.println("\r\n出队列操作--------------------------");
// while (!queue.isEmpty()) {
// System.err.print(queue.deQueue() + "\t");
// }

System.out.println("\r\n清空队列操作--------------------------");
queue.clear();

System.out.println("\r\nQUEUE SIZE: " + queue.size);