Java队列的两种实现方式
1. 基于数组
package Algorithm.learn; import java.util.Arrays; /** * Created by liujinhong on 2017/3/7. */ public class ArrayQueue<E> { Object[] queue; int size; public ArrayQueue() { queue = new Object[10]; } public boolean isEmpty() { return size == 0; } public E poll() { if (isEmpty()) return null; E data = (E) queue[0]; System.arraycopy(queue, 1, queue, 0, size-1); size--; return data; } private void ensureCapacity(int size) { if (size > queue.length) { int len = queue.length + 10; queue = Arrays.copyOf(queue, len); } } public void offer(E data) { ensureCapacity(size+1); queue[size++] = data; } public static void main(String[] args) { ArrayQueue<Integer> queue = new ArrayQueue<>(); for (int i = 0; i < 20; i++) { queue.offer(i); } for (int i = 0; i < 20; i++) { System.out.println(queue.poll()); } } }
2. 基于链表
package Algorithm.learn; /** * Created by liujinhong on 2017/3/7. * 基于链表实现队列 */ public class ListQueue<E> { class Node<E> { Node<E> next = null; E data; public Node(E data) { this.data = data; } } private Node<E> head = null; private Node<E> tail = null; public boolean isEmpty() { return head == null; } public void offer(E e) { Node<E> node = new Node<E>(e); if (isEmpty()) { head = node; tail = node; return; } tail.next = node;
tail = node; } public E poll() { if (isEmpty()) return null; E data = head.data; head = head.next; return data; } public int size() { Node<E> temp = head; int len = 0; while (temp != null) { len++; temp = temp.next; } return len; } public static void main(String[] args) { ListQueue<String> queue = new ListQueue<>(); queue.offer("a"); queue.offer("b"); System.out.println(queue.poll()); System.out.println(queue.poll()); } }