queue.java

来自「这里面包含有栈」· Java 代码 · 共 89 行

JAVA
89
字号
package org.huhuiyu.datastructures;

public class Queue<T> {
	private Node<T> head; // 头节点
	private Node<T> tail; // 尾节点
	private int count;

	public Queue() {
		clear();
	}

	/**
	 * 加入数据到队列
	 * 
	 * @param data
	 *            加入到队列的数据
	 */
	public void enqueue(T data) {
		Node<T> add = new Node<T>(data);
		if (isEmpty()) {
			head = add;
			tail = head;
		}
		else {
			// 添加到尾部
			tail.setNext(add);
			tail = add;
		}
		count++;
	}

	/**
	 * 出队并返回出队的数据
	 * 
	 * @return 出队的数据
	 */
	public T dequeue() {
		if (isEmpty()) {
			throw new IllegalStateException("队列是空的!");
		}
		// 移除并返回头数据
		T data = head.getData();
		head = head.getNext();
		count--;
		if (isEmpty()) {
			tail = null; // 置空尾指针
		}
		return data;
	}

	/**
	 * 查看排在队列最前端的数据
	 * 
	 * @return 排在队列最前端的数据
	 */
	public T peek() {
		if (isEmpty()) {
			throw new IllegalStateException("队列是空的!");
		}
		return head.getData();
	}

	public void clear() {
		head = null;
		tail = null;
		count = 0;
	}

	public boolean isEmpty() {
		return count == 0;
	}

	public int size() {
		return count;
	}

	public static void main(String[] args) {
		Queue<Integer> queue = new Queue<Integer>();
		for (int i = 1; i <= 10; i++) {
			queue.enqueue(i);
		}
		System.out.println("size():" + queue.size());
		while (!queue.isEmpty()) {
			System.out.println(queue.dequeue());
		}
		System.out.println("size():" + queue.size());
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?