队列实现 java版本

public class Queue<T> implements Iterable<T>{
	private class Node{//定义节点类
		T item;
		Node nextNode;
	}
	private Node firstNode;
	private Node lastNode;
	private int N;
	
	public boolean isEmpty(){
		return firstNode == null;
	}
	
	public int size(){
		return N;
	}
	
	public void enQueue(T item){// 队尾插入新节点
		Node oldNode = lastNode;
		lastNode = new Node();
		if (isEmpty()) {
			firstNode = lastNode;
		}
		else{
			oldNode.nextNode = lastNode;
		}
		N++;
	}
	
	public T deQueue(){// 队首插入新节点
		T item = firstNode.item;
		firstNode = firstNode.nextNode;
		if(isEmpty())
			lastNode = null;
		N--;
		return item;
	}
	// 以下实现Iterator 接口 ,方便迭代输出 , 可选实现
	public Iterator iterator(){
		return new queueIterator();
	}
	
	private class queueIterator implements Iterator<T>{
		Node iteratorNode = firstNode;
		@Override
		public boolean hasNext() {
			return iteratorNode != null;
		}

		@Override
		public T next() {
			T item = (T) iteratorNode.item;
			iteratorNode = iteratorNode.nextNode;
			return item;
		}
		
	}
	
}

点赞