时间复杂度O(1)
//使用单向链表实现队列
public class Code01_LinkedListToQueue {
public static class Node<V>{
public V value;
public Node<V> next;
public Node(V v){
value = v;
next = null;
}
}
public static class MyQueue<V>{
private Node<V> head;
private Node<V> tail;
private int size;
public void offer(V value){
Node<V> cur = new Node<V>(value);
if(tail == null){
head = cur;
tail = cur;
}else{
//这里是放入的时候,将当前尾部的指针指到新的节点
tail.next = cur;
//然后将尾部修改成新加入的节点,方便下次装入数据
tail = cur;
}
size++;
}
public V pool(){
V ans = null;
if(head !=null){
ans = head.value;
head = head.next;
size -- ;
}
//这里判断的原因是,如果数据都取完后,要保证尾巴也为空,不然就是头部已经等于空了,尾巴指针数据还没有释放
if(head ==null){
tail = null;
}
return ans;
}
public V peek(){
V ans = null;
if(head != null){
ans = head.value;
}
return ans;
}
public boolean isEmpty(){
return size == 0 ? true:false;
}
public int size(){
return size;
}
}
}