java----队列(Queue和Deque)

一、Queue概念

  1. 队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(First In First Out)。
  2. 入队列:进行插入操作的一端称为队尾(Tail/Rear)
  3. 出队列:进行删除操作的一端称为队头(Head/Front)
  4. 图示
    在这里插入图片描述

二、Queue队列实现

队列也可以数组和链表的结构实现,使用链表的结构实现更优一些,因为如果使用数组的结构,出队列在数组头上出数据,效率会比较低。

  • 链表实现队列图示
    在这里插入图片描述
  • 代码示例
public class Node {
    private int val;
    private Node next;
    public Node (int val){
        this.val = val;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    public Node getNext() {
        return next;
    }

    public int getVal() {
        return val;
    }
}
public class MyQueue {
    private Node first;
    private Node last;

    //入队
    public void offer(int val){
        //尾插法:判断是不是第一次插入
        Node node = new Node(val);
        if(this.first == null){
            this.first = node;
            this.last = node;
        } else{
            this.last.setNext(node);//last.next = node;
            this.last = node;
        }
    }

    //出队
    public int poll(){
        //判断是否为空
        if(isEmpty()){
            throw new UnsupportedOperationException("对列为空");
        }
        int ret = this.first.getVal();
        this.first = this.first.getNext();//this.first = this.first.next;
        return ret;
    }

    public boolean isEmpty(){
        return this.first == null;
    }

    //得到队头元素但是不删除
    public int peek(){
        //判断是否为空
        if(isEmpty()){
            throw new UnsupportedOperationException("对列为空");
        }
        return this.first.getVal();
    }
}
public class QueueTest {
    public static void main(String[] args) {
        MyQueue myQueue = new MyQueue();
        myQueue.offer(1);
        myQueue.offer(3);
        System.out.println(myQueue.peek()); //1
        System.out.println(myQueue.poll()); //1
        System.out.println(myQueue.peek()); //3
        System.out.println(myQueue.isEmpty()); // false
    }
}

三、使用方法

1、Queue

在这里插入图片描述

2、Deque

在这里插入图片描述

总结

以上就是今天要讲的内容,本文仅仅简单介绍了Queue的实现,而在Queue和Deque中提供了能使我们快速便捷地处理数据的函数和方法。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值