- /**
- * 队列的实现<br>
- *
- */
- public class Queue<T> {
- //节点类
- private static class Node<T>{
- T data;
- Node<T> next;
- public Node(T t){
- data = t;
- next = null;
- }
- }
- private int size; //链表长度
- private Node<T> front; //队列头节点
- private Node<T> rear; //队列尾节点
- /**
- * 创建一个空队列
- */
- public Queue(){
- front = null;
- rear = null;
- size = 0;
- }
- /**
- * 创建一个队列,包含一个数据
- * @param data 数据
- */
- public Queue(T data){
- front = new Node<T>(data);
- rear = front;
- size = 1;
- }
- /**
- * 向队列尾部添加一个数据
- * @param data 数据
- */
- public void add(T data){
- //如果是控队列,创建一个新的节点并指向他
- if(isEmpty()){
- front = new Node<T>(data);
- rear = front;
- }else{
- Node<T> temp = new Node<T>(data);
- //向尾部添加节点
- rear.next = temp;
- //将尾节点指向新创建的节点
- rear = temp;
- }
- size++;
- }
- /**
- * 移除队列头节点数据
- * @return 头节点数据
- */
- public T remove(){
- //如果是空队列,返回null
- if(isEmpty()){
- return null;
- }else{
- //获得头节点的数据
- T t = front.data;
- //头节点指向下一个数据
- front = front.next;
- size--;
- return t;
- }
- }
- /**
- * 获得队列中最后一个数据
- * @return 最后一个数据
- */
- public T lastElement(){
- if(isEmpty()){
- return null;
- }else{
- return rear.data;
- }
- }
- /**
- * 判断是否为空队列
- * @return 空队列为true,非空队列为true
- */
- public boolean isEmpty(){
- return size == 0;
- }
- /**
- * 清空队列
- */
- public void clear(){
- front = null;
- rear = null;
- size = 0;
- }
- /**
- * 获得队列的长度
- * @return 长度
- */
- public int length(){
- return size;
- }
- /**
- * 输出队列
- */
- public void printLink(){
- if(isEmpty()){
- System.out.println("空队列!");
- }else{
- Node<T> temp = front;
- while(temp!=null){
- System.out.print(temp.data+" ");
- temp = temp.next;
- }
- System.out.println();
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/1905201512603.html
来源: http://www.codesnippet.cn/detail/1905201512603.html