用链表来实现队列这种数据结构
public class Node<E> {
E data;
Node next;
public Node(E data) {
this.data = data;
}
}
public class MyQueue<E> {
private Node<E> head = null;
private Node<E> tail = null;
public boolean isEmpty() {// 如果头和尾都是null,认为是空的
if (head == null && tail == null) {
return true;
} else {
return false;
}
}
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 = newNode;
}
}
public E pop() {
if (this.isEmpty()) {
return null;
}
E data = head.data;
head = head.next;
if (head == null) {
tail = null;
}
return data;
}
public int size() {
Node<E> tmp = head;
int n = 0;
while (tmp != null) {
n++;
tmp = tmp.next;
}
return n;
}
}
用数组实现队列
实现多线程安全,增加了对队列操作的同步
import java.util.LinkedList;
public class MyQueue<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 isEmpty() {
return size == 0;
}
public synchronized int size() {
return size;
}
}