队列在数据结构中非常基础,尤其是出队和入队的算法很有意思。可以好好看看,多多理解一下
package java11to20;
public class D17_LinkedQueue {
class Node {
int data;
Node next;
public Node(int par) {
data = par;
next = null;
}
}
Node header;
Node tail;
public static void main(String[] args) {
D17_LinkedQueue linkQueue = new D17_LinkedQueue();
System.out.println("初始化,列表为:" + linkQueue.toString());
for (int i = 0; i < 7; i++) {
linkQueue.enqueue(i + 1);// 入队
}
System.out.println("入队完毕,队列为:" + linkQueue.toString());
linkQueue.dequeue();// 出队
System.out.println("出队完毕,队列为:" + linkQueue.toString());
int value;
for (int i = 0; i < 7; i++) {
value = linkQueue.dequeue();
System.out.println(String.format("出队值 %s,最新队列为:%s", value, linkQueue.toString()));
}
}
public D17_LinkedQueue() {
header = new Node(-1);
header.next = null;
tail = header;
}
public void enqueue(int par) {
Node node = new Node(par);
tail.next = node;
tail = node;
}
public int dequeue() {
if (header.next == null) {
System.out.println("队空");
return -1;
}
int resultValue = header.next.data;
header.next = header.next.next;
return resultValue;
}
public String toString() {
String result = "";
if (header.next == null) {
return "空";
}
Node node = header.next;
while (node != null) {
result += node.data + ",";
node = node.next;
}
return result;
}
}
输出结果:
初始化,列表为:空
入队完毕,队列为:1,2,3,4,5,6,7,
出队完毕,队列为:2,3,4,5,6,7,
出队值 2,最新队列为:3,4,5,6,7,
出队值 3,最新队列为:4,5,6,7,
出队值 4,最新队列为:5,6,7,
出队值 5,最新队列为:6,7,
出队值 6,最新队列为:7,
出队值 7,最新队列为:空
队空
出队值 -1,最新队列为:空