实现队列比实现栈的会多一点复杂,需要两个标记,first表示队头,last表示队尾。
链表结构
private class Node{Item item;Node next;}
迭代器
与实现栈的迭代器一模一样
private class Iterator implements java.util.Iterator<Item>{private Node p=first;@Overridepublic boolean hasNext() {return p!=null;}@Overridepublic Item next() {Item item=p.item;p=p.next;return item;}@Overridepublic void remove() {}}
源代码
static class queue<Item>{private Node first;//队头private Node last;//队尾private int N;private class Node{Item item;Node next;}private boolean isEmpty(){return first==null;}private int size(){return N;}private void enqueue(Item item){//入队Node oldlast=last;last=new Node();last.item=item;last.next=null;if(isEmpty()){//如果队列为空,则first需要和last指向相同first=last;}else {//队列不为空的话,就是正常情况直接last指向队尾的下一个位置(nulloldlast.next=last;}N++;}private Item dequeue(){//出队Item item=first.item;first=first.next;if(isEmpty()){//如果队里没有元素的话,last得为空last=null;}N--;return item;}private Iterator iterator(){return new Iterator();}private class Iterator implements java.util.Iterator<Item>{private Node p=first;@Overridepublic boolean hasNext() {return p!=null;}@Overridepublic Item next() {Item item=p.item;p=p.next;return item;}@Overridepublic void remove() {}}}
简单实例
public static void main(String[] args) {queue<Integer> stringqueue = new queue<Integer>();System.out.println("入队中... ...");for(int i=1;i<=9;i++){stringqueue.enqueue(i);}queue<Integer>.Iterator iterator = stringqueue.iterator();System.out.println("迭代中... ...");while(iterator.hasNext()){System.out.print(iterator.next()+" ");}System.out.println();System.out.println("---我是分割线---"+"\n"+"出队中... ...");while (!stringqueue.isEmpty()){System.out.print(stringqueue.dequeue()+" ");}if(stringqueue.size()==0){System.out.println("出队完毕!");}}