//链表实现队列
class Node<E>{
Node<E> next = null;
E data;
public Node(E data){
this.data = data;
}
}
public class ListQueue<E>{
private Node<E> head = null;
private Node<E> tail = null;
public boolean empty(){
return head==null;
}
public void put(E data){
Node<E> newNode = new Node<E> (data);
if(head == null && tail == null){
head = tail = newNode;
}
else{
tail.next = newNode;
tail = tail.next;
}
}
public E pop(){
if(this.empty()){
return null;
}
E data = head.data;
head = head.next;
return data;
}
public int size(){
Node<E> tmp = head;
int n = 0;
while(tmp != null){
n++;
tmp = tmp.next;
}
return n;
}
public static void main(String[] args){
ListQueue<Integer> q = new ListQueue<Integer>();
q.put(2);
q.put(5);
q.put(6);
System.out.println("The length:" + q.size());
System.out.println("The first element:"+ q.pop());
}
}
下面介绍数组实现队列的方式,为了实现多线程安全,增加了对队列操作的同步。
//数组实现队列
import java.util.LinkedList;
public class ArrayQueue<E>{
private LinkedList<E> list = new LinkedList<E>();
private int size = 0;
public synchronized void put(E e){
list.addLast(e);
size++;
}
public synchronized E pop(){
size--;
return list.removeFirst();
}
public synchronized boolean empty(){
return size==0;
}
public synchronized int size(){
return size;
}
}