public class MyQueue <T>{
private int size;
private Node<T> head=null;
private Node<T> tail=null;
private static class Node<U>{
U value;
Node<U> next;
Node(U value){
this.value=value;
}
}
public void offer(T value){
Node<T> node=new Node<>(value);
if(tali==null){
head=tail=node;
}else {
tail.next=node;
}
tali=node;
size++;
}
public T poll(){
if(size==0){
return null;
}
Node oldHead=head;
head=head.next;
if(head==null){
tail=null;
}
size--;
return (T) oldHead.value;
}
public boolean isEmpty(){
return size==0;
}
public T peek(){
if(size==0){
throw new RuntimeException("the queue is empty");
}
return head.value;
}
public static void main(String[] args) {
MyQueue<String> queue=new MyQueue<>();
for(String s:"A B C D E F G H I J K".split(" ")){
queue.offer(s);
}
String str=null;
while (!((str=queue.poll())==null)){
System.out.print(str+“ ”);
}
}
}
试试效果
A B C D E F G H I J K
Process finished with exit code 0