链式队列

一、链式队列

队列的链式表示称为链式队列,其实也就是一个操作受限的单链表

要一个单链表具有队列的性质,即先进先出,在编写代码之前,需要明确:

  • 入队:链表添加元素也就是入队列需要采用的是尾插法,即在队尾添加元素;

  • 出队:队列不为空时,出队列应该为删除头结点后的第一个结点;


如图:
在这里插入图片描述

二、实现一个链式队列
  1. 数据结构
class Queue<E> {
    class Entry<E> {
        E data;
        Entry<E> next;
        public Entry() {
            this.data = null;
            this.next = null;
        }

        public Entry(E val) {
            this.data = val;
            this.next = null;
        }
    }

    private Entry<E> front; //头指针 也就是队首
    private Entry<E> rear; //尾指针 即队尾
    private int usedSize; //队列元素个数

    public Queue() {
        this.front = null;
        this.rear = null;
        this.usedSize = 0;
    }
}
  1. 具体操作
  • 判空
    //判空
    public boolean isEmpty() { //当usedSize等于时说明队列为空
        return this.usedSize == 0;
    }
}
  • 获取队列长度
    public int getUsedSize() {
        return usedSize; //外部可以获取队列中元素的个数
    }
  • 入队列
    //入队列
    public void push(E val) {
        Entry<E> entry = new Entry<>(val);
        if (isEmpty()) { //在空队列第一个有元素入队时,需指定头指针与尾指针
            this.front = entry; //此时头尾指针都是entry
            this.rear = front;
        } else { //队列不为空时,入队操作只需将新的元素结点放在rear的后面,然后rear指针后移
            this.rear.next = entry;
            this.rear = rear.next;
        }
        this.usedSize++;
    }
  • 出队列
    //出队列
    public void pop() {
        if (isEmpty()) { //在出队操作时首先要判断队列是否为空
            throw new UnsupportedOperationException("不支持的操作");
        }
        //当队列不为空时,删除front指针所指结点,只需将front指针后移即可
        this.front = this.front.next;
        this.usedSize--; 
    }
  • 获取队首元素
    //获取队首元素
    public E peek() {
        if (isEmpty()) { //在队列是否为空时队首元素不存在
            throw new UnsupportedOperationException("不支持的操作");
        }
        //当队列不为空时,只需返回front指针所指结点元素值即可
        return this.front.data;
    }
  • 打印队列元素
    //打印
    public void show() {
        Entry cur = this.front;
        while (cur != null) {
            System.out.print(cur.data + " ");
            cur = cur.next;
        }
        System.out.println();
    }

相关内容:单链表常用方法单链表相关面试真题

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值