队列的链式存储

队列也是一种特殊的线性表,他的链式存储和单链表基本相同,只是增加和删除是固定了位置而已。
队列的链式存储叫做链队列。一般将队头指针指向队头,而将队尾指针指向队尾。

在这里插入图片描述
链队列的简单实现
结点代码如下

public class Node<T>{
    T date;
    Node<T> next;
    public Node(){
        this(null);
    }
    public Node(T value){
        date = value;
        next = null;
    }
}

队列代码如下

public class MyQueue<T extends Comparable<T>> {
    private Node<T> front;          //队首
    private Node<T> rear;           //队尾
    private int size;
    public MyQueue(){
        front = new Node<>();
        rear = front;
        size = 0;
    }
    //判队空
    public boolean isEmpty(){
        return front == rear;
    }
    //入队
    public void offer(T value){
        Node n = new Node(value);
        n.next = null;
        rear.next = n;
        rear = n;
        size++;
    }
    //出队
    public T poll(){
        Node temp;
        if (isEmpty()){
            throw new NullPointerException();
        }else{
            temp = front;
            T data = (T)temp.next.date;
            front.next = front.next.next;
            temp = null;                        //防止内存泄漏
            size--;
            return data;
        }
    }
    //获取队首元素
    public T peek(){
        if (isEmpty()){
            throw new NullPointerException();
        }else{
            return front.next.date;
        }
    }
    //获取队列长度
    public int size(){
        return size;
    }
    //打印队列
    public void show(){
        Node temp = front;
        while (temp != rear){
            System.out.println(temp.next.date);
            temp = temp.next;
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值