什么是链队列
链队是指采用链式存储结构实现的队列,通常链队用单链表俩表示。一个链队显然需要两个分别指示队头和队尾的指针,也称为头指针和尾指针,有了这两个指针才能唯一的确定。
package 链队列;
public class LinkQueue {
class Element {
Object data;
Element next;
public Element() {
this.data = null;
this.next = null;
}
public Element(Object data) {
this.data = data;
this.next = null;
}
public Element(Object data, Element next) {
this.data = data;
this.next = next;
}
}
private Element front;
private Element rear;
public LinkQueue() {
front = null;
rear = null;
}
public void enQueue(Object data) {
Element e = new Element(data);
if(this.front != null) {
this.rear.next = e;
rear = e;
}
else {
this.front = this.rear = e;
}
}
public void deQueue() {
if(this.front != null) {
Element p = front;
front = front.next;
if(p == rear) { //队列中只有一个元素
rear = null;
}
}
else System.out.println("队列为空");
}
public Object getHead() {
if(front != null) {
return front.data;
}
else return null;
}
public int getLength() {
Element p = front;
int length = 0;
while(p != null) {
p = p.next;
length++;
}
return length;
}
public boolean isEmpty() {
return front == null ? true : false;
}
public static void main(String[] args) {
LinkQueue q = new LinkQueue();
System.out.println("队列是否为空:" + q.isEmpty());
System.out.println("连续入队=========");
for (int i = 0; i < 5; i++) {
q.enQueue(i);
}
System.out.println("队列的长度为: " + q.getLength());
System.out.println("队首元素为:" + q.getHead());
System.out.println("连续出队=========");
for (int i = 0; i < 3; i++) {
q.deQueue();
}
System.out.println("队列是否为空:" + q.isEmpty());
System.out.println("队列的长度为: " + q.getLength());
System.out.println("队首元素为:" + q.getHead());
}
}