队列抽象数据结构之一,遵循FIFO原则,通过在初始化时构造队首和队尾两个引用(指针)指向一个空节点,作为空队列的标志
package com.shine.test.datastruct;
import java.util.EmptyStackException;
public class LinkQueue<E> {
private Node front,tail;
class Node {
E data;
Node next;
}
public LinkQueue() {
LinkQueue<E>.Node node = new Node();
node.data = null;
node.next = null;
front = tail = node;
}
public boolean push(E e) {
LinkQueue<E>.Node temp = new Node();
temp.data = e;
temp.next = null;
tail.next = temp; //当加入第一个元素是应为tail和front指向同一个对象 所以此时相当于front.next =temp,但以后不是
tail = temp;
if(temp != null) {
return true;
}
return false;
}
public E pop() {
if(front == tail) {
throw new EmptyStackException();
}else {
LinkQueue<E>.Node temp = front.next;
E e = temp.data;
front.next = temp.next;
if(tail == temp) { //当队列中只有一个元素时 需要将队列置空
tail = front;
}
return e;
}
}
public E peek() {
if(front == tail) {
throw new EmptyStackException();
}else {
LinkQueue<E>.Node temp = front.next;
E e = temp.data;
return e;
}
}
}