一、队列定义
1.队列是先进献出的数据结构,是一种只能在一端插入一端删除的线性表
2.基本实现
1)判断队列是否为空
2)输出队列长度
3)进队、出队
public class Queue<T> implements Iterable<T> { //头结点 private Node head; //尾结点 private Node last; //队列长度 private int N; //节点类 public class Node{ public T item; public Node next; public Node(T item, Node next) { this.item = item; this.next = next; } } //初始化队列 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 void insert(T t){ //判断尾结点是否为null if(last==null){ //尾结点为空,创建一个结点设为尾结点 last=new Node(t,null); //都节点指向尾结点 head.next=last; }else{ //尾结点不为空,创建一个新结点 Node oldLast=last; last= new Node(t, null); //让尾结点指向新的结点,让新的结点为尾结点 oldLast.next=last; } N++; } //从队列中拿出一个元素 public T remove(){ if (isEmpty()){ return null; } //得到首结点 Node n = head.next; //头结点指向当前结点的下一个结点 head.next=n.next; N--; //判断删除之后队列是否为空,若为空,则将尾结点置为空 if (isEmpty()){ last=null; } return n.item; } //遍历 @Override public Iterator<T> iterator() { return new SIterator(); } public class SIterator implements Iterator{ private Node n; public SIterator() { this.n = head; } @Override public boolean hasNext() { return n.next!=null; } @Override public Object next() { n=n.next; return n.item; } } }