//对列用链表简单实现
package 队列链表;
class QueueNode {
QueueNode next;
Object Data;
QueueNode(Object obj) {
this.Data = obj;
}
}
public class QueueLinked {
QueueNode front; // 队首指针
QueueNode rear; // 队尾指针
QueueLinked() {
this.front = null;
this.rear = null;
}
public void add(Object obj) { //入队
if (front == null && rear == null) {
rear = new QueueNode(obj);
front = rear;
}
QueueNode queue = new QueueNode(obj);
rear.next = queue;
rear = rear.next;
}
public Object poll() { //获取但不移除此队列的头;如果此队列为空,则返回 null。
if (front == null) {
return null;
}
if (front == rear && rear != null) {//只有一个元素了
QueueNode node = front;
front = null;
rear = null;
return node.Data;
}
Object obj = front.Data;
front = front.next;
return obj;
}
public Object peek() {//获取但不移除此队列的头;如果此队列为空,则返回 null。
if (front == null) {
return null;
}
Object obj = front.Data;
return obj;
}
public static void main(String[] args) {
QueueLinked queue = new QueueLinked();
System.out.println(queue.poll());
}
}