一.节点类
/**
* @author 2902996750
* @version 1.0
* @date 2022/10/8 16:58
* 队列所需节点
*/
public class Node<T> {
T item;
Node<T> next;
public Node(T item, Node<T> next) {
this.item = item;
this.next = next;
}
}
二.实现队列
import java.util.Iterator;
/**
* @author 2902996750
* @version 1.0
* @date 2022/10/8 16:56
*/
public class Queue<T> implements Iterable{
/**
* 队列的头结点
*/
Node<T> head;
/**
* 队列的尾结点
*/
Node<T> last;
/**
* 队列中的节点个数
*/
int count;
public Queue() {
this.head = new Node<T>(null,null);
this.last = null;
this.count = 0;
}
/**
* 判断队列是不是空
*/
public boolean isEmpty(){
return count==0;
}
/**
* 判断队列中元素的个数
*/
public int size(){
return count;
}
/**
* 向队列中插入元素
*/
public void insert(T t){
if (last==null){
Node<T> node = new Node<>(t, null);
head.next=node;
last=node;
count++;
}else {
Node<T> node = new Node<>(t, null);
last.next=node;
last=node;
count++;
}
}
/**
* 删除队列中的元素
*/
public T remove(){
if (isEmpty()){
return null;
}else {
Node<T> next = head.next;
head.next=head.next.next;
count--;
//如果队列中所有数据全部删完,那么重置last
if (isEmpty()){
last=null;
}
return next.item;
}
}
@Override
public Iterator iterator() {
return new Titerator(head);
}
}
三.实现迭代器
import java.util.Iterator;
/**
* @author 2902996750
* @version 1.0
* @date 2022/10/6 18:41
*/
public class Titerator implements Iterator {
private Node node;
public Titerator(Node node) {
this.node = node;
}
@Override
public boolean hasNext() {
return node.next!=null;
}
@Override
public Object next() {
node = node.next;
return node.item;
}
}
四.测试类
import java.util.Iterator;
/**
* @author 2902996750
* @version 1.0
* @date 2022/10/8 17:29
*/
public class Test {
public static void main(String[] args) {
Queue<Object> objectQueue = new Queue<>();
objectQueue.insert("a");
objectQueue.insert("b");
objectQueue.insert("c");
objectQueue.insert("d");
objectQueue.insert("f");
Iterator iterator = objectQueue.iterator();
while (iterator.hasNext()){
Object next = iterator.next();
System.out.println(next);
}
System.out.println("第一个删除的元素是:"+objectQueue.remove());
System.out.println("队列的个数:"+objectQueue.size());
}
}