数据结构-队列-Java实现
队列:先进先出
实现:链表形式
import java.util.Iterator;
/**
* 队列
*/
public class Queue<T> implements Iterable<T>{
private Node<T> head;//队头
private int N;//对列内结点个数
private Node<T> last;//队尾
//初始化队列
public Queue() {
this.head = new Node<>(null, null);
this.last = null;
this.N = 0;
}
//判断队空
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
//出队
public T dequeue() {
if (isEmpty()) {
throw new RuntimeException("队列为空,无法出队");
}
Node<T> result = head.next;
head.next = head.next.next;
N--;
if (isEmpty()) {
last = null;
}
return result.item;
}
//入队
public void enqueue(T t) {
if (last == null) {
//当前队列为空,插入第一个结点,此时head.next 和 last 都指向第一个结点;
last = new Node<>(t, null);
head.next = last;
} else {
//队列不为空,此时需要将原最后一个结点的next = 新节点。且last = 新节点
Node oldLast = last;
last = new Node<>(t, null);
oldLast.next = last;
}
N++;
}
@Override
public Iterator<T> iterator() {
return new SIterator<>();
}
private class SIterator<T> implements Iterator<T>{
Node shead = head;
@Override
public boolean hasNext() {
return shead.next != null;
}
@Override
public T next() {
Node<T> node = shead.next;
shead = shead.next;
return node.item;
}
}
private class Node<T> {
T item;
Node<T> next;
public Node(T item, Node<T> node) {
this.item = item;
this.next = node;
}
}
}
易忘点:在Iterator中next方法中,不要忘记进行结点的后移。