package org.Stone6762.MQueue.imple;
import org.Stone6762.MQueue.MQueue;
import org.Stone6762.entity.Node;
/**
* @ClassName_LinkQueue队列的链式存储
* @author_Stone6762
* @Description_
*/
public class LinkQueue implements MQueue {
/**
* @front指向队首结点
*/
private Node front;
/**
* @rear指向队尾结点
*/
private Node rear;
public LinkQueue() {
front = rear = null;
}
@Override
public void clear() {
front = rear = null;
}
@Override
public boolean isEmpty() {
return front == null;
}
@Override
public int length() {
int length = 0;
if (front != null) {
// 创建一个指针指向队首元素,然后移动该指针,而不是移动队首元素,因为队首元素和队尾元素只有当出对和入队时才移动
Node t = front;
while (t != null) {
t = t.getNext();
length++;
}
}
return length;
}
@Override
public Object peek() {
if (front != null) {
return front.getData();
} else {
return null;
}
}
@Override
public void offer(Object data) throws Exception {
Node newNode = new Node(data);
/*
* 插入第一个元素时必须特殊处理
*/
if (front != null) {
rear.setNext(newNode);
rear = newNode;
} else {
front = rear = newNode;
}
}
@Override
public Object poll() {
if (front != null) {
Node t = front;
front = front.getNext();
/*
* 删除时,对最后一个元素进行判断
*/
if (t == rear) {
rear = null;
}
return t.getData();
} else {
return null;
}
}
}