package linkede;
/** 队列 (单链表)
* @author codelmh
* @data 2021/12/9
*/
public class MyQueue<T> {
private Node head; // 指向 头结点
private Node tail;//指向尾结点
private Integer size; // 大小
public T peek(){
if (head == null){
return null;
}
return head.value;
}
/**
* 弹出一个节点
*/
public T poll(){
if (head == null){
return null;
}
Node cur = head;
head = cur.next;
size --;
return cur.value;
}
/**
* 尾插
* @param value
*/
public void offer(T value){
//新节点
Node newNode = new Node(value);
// head为空说明队列为空
if ( this.head == null){
this.head = newNode;
this.tail = newNode;
return;
}
this.tail.next = newNode;
this.tail = newNode;
}
/**
* 头插法
* @param value
*/
public void addHead(T value){
//新节点
Node newNode = new Node(value);
// head为空说明队列为空
if ( this.head == null){
this.head = newNode;
this.tail = newNode;
return;
}
// 新节点的netx域 指向 头指针
newNode.next = head;
// 头指针指向 newNode
head = newNode;
size ++;
}
public MyQueue() {
this.head = null;
this.tail = null;
this.size = 0;
}
private class Node {
T value; //数据
Node next; //指针
// 节点初始化
public Node(T value) {
this.next = null;
this.value = value;
}
}
}
本人小白一枚,若有错误请指正!