基于链表实现的队列
时间复杂度:
入队:O(1)
出队:O(1)
接口类:
public interface Queue<E> {
void enqueue(E e);
E dequeue();
E getFront();
int getSize();
boolean isEmpty();
}
实现类
public class LinkedListQueue<E> implements Queue<E> {
//结点类
class Node{
public Node next;
public E e ;
public Node(E e,Node next){
this.e = e;
this.next = next;
}
public Node(E e){
this(e,null);
}
public Node(){
this(null,null);
}
}
private Node head;//头结点
private Node tail;//尾结点
private int size;
//初始化
public LinkedListQueue(){
head = null;
tail = null;
size = 0;
}
@Override
public void enqueue(E e) {
//队空
if (tail == null){
Node node = new Node(e);
tail = node;
head = tail;
}
else {
Node node = new Node(e);
tail.next = node;
tail = tail.next;
}
size++;
}
@Override
public E dequeue() {
if (isEmpty()){
throw new IllegalArgumentException("队列为空,无法删除元素");
}
Node reNode = head;
head = head.next;
reNode.next = null;
//删除后队空了
if (head == null){
tail =null;
}
size--;
return reNode.e;
}
@Override
public E getFront() {
if (isEmpty()){
throw new IllegalArgumentException("队列为空");
}
return head.e;
}
@Override
public int getSize() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public String toString() {
StringBuilder res = new StringBuilder();
res.append("LinkedListQueue: front");
Node cur = head;
while (cur != null){
res.append(cur.e + "->");
cur = cur.next;
}
res.append("NULL tail");
return res.toString();
}
}
测试:
public class Main {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedListQueue<>();
for (int i = 0 ; i < 9 ; i ++){
queue.enqueue(i);
System.out.println(queue);
}
for (int i = 0 ; i < 5 ; i++)
queue.dequeue();
System.out.println(queue);
for (int i = 0 ; i < 5 ; i ++){
queue.enqueue(i);
}
System.out.println(queue);
System.out.println(queue.getFront());
System.out.println(queue.getSize());
}
}