赞
踩
队列的概念:队列和栈类似,都属于线性逻辑数据结构,与栈不同的是。队列中的元素是先进先出(First In First Out,简称FIFO)的。队列的出口断叫做队头,队列的入口端叫做队尾。队列和栈一样可以用数组实现,也可以用链表实现。用数组实现的叫做顺序队列,用链表实现的叫做链式队列。
数组实现
public class ArrayQueue<T> { private int length; private T[] array; private int size = 0; public ArrayQueue(int length) { this.length = length; this.array = (T[]) new Object[length]; } public ArrayQueue() { this(16); } /** * 入队 * @param param 入队参数 */ public void inQueue(T param){ if (size >= length){ throw new RuntimeException("The queue is full"); } array[size] = param; size++; } /** * 出队 * @return 出队的数据 */ public T outQueue(){ if (size <= 0){ throw new RuntimeException("The queue is null"); } T result = array[0]; // 可用System.arraycopy()替代 for (int i = 0; i < size-1; i++) { array[i] = array[i+1]; } size--; return result; } public static void main(String[] args) { ArrayQueue<String> stringArrayQueue = new ArrayQueue<>(); stringArrayQueue.inQueue("s"); stringArrayQueue.inQueue("o"); stringArrayQueue.inQueue("u"); stringArrayQueue.inQueue("t"); System.out.println(stringArrayQueue.outQueue()); System.out.println(stringArrayQueue.outQueue()); System.out.println(stringArrayQueue.outQueue()); System.out.println(stringArrayQueue.outQueue()); } }
链表实现
public class Node<T> {
public T data;
public Node<T> next;
public Node(T data) {
this.data = data;
}
}
public class LinkedListQueue<E> { private Node<E> head; private Node<E> tail; private int size = 0; /** * 入队 * @param e 入队参数 */ public void inQueue(E e){ final Node<E> temp = tail; final Node<E> newNode = new Node<>(e); tail = newNode; if (temp == null){ head = newNode; }else{ temp.next = newNode; } size++; } /** * 出队 * @return 出队数据值 */ public E outQueue(){ if (size <= 0){ throw new NullPointerException("The queue is null"); } Node<E> oldHead = head; head = head.next; oldHead.next = null; size--; return oldHead.data; } public static void main(String[] args) { LinkedListQueue<Integer> listQueue = new LinkedListQueue<>(); listQueue.inQueue(1); listQueue.inQueue(2); listQueue.inQueue(3); listQueue.inQueue(4); System.out.println(listQueue.outQueue()); System.out.println(listQueue.outQueue()); System.out.println(listQueue.outQueue()); System.out.println(listQueue.outQueue()); System.out.println(listQueue.outQueue()); } }
时间复杂度:入队和出队都是O(1)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。