数据结构|队列(Queue)

1. 队列

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

2. Java中的组织关系

在这里插入图片描述
创建队列
LinkedList 实现了 Queue 接口。

Queue<String> queue = new LinkedList<>();

3. 实现自己的队列Queue - MyQueue

public class Node {
    int val;
    Node next;

    Node(int val, Node next){
        this.val = val;
        this.next = next;
    }

    Node(int val){
        this(val, null);
    }
}

public class MyQueue {
    private Node head = null;
    private Node tail = null;
    private int size = 0;

    public void offer(int v){
        Node node = new Node(v);
        if (tail == null){
            head = node;
        }else {
            tail.next = node;
        }
        tail = node;
        size++;
    }

    public int poll(){
        if (size == 0){
            throw new ArrayIndexOutOfBoundsException();
        }
        if (size == 1){
            head = tail = null;
            size = 0;
            return head.val;
        }else {
            Node deleteNode = head;
            head = head.next;
            size--;
            return deleteNode.val;
        }
    }

    public int peek(){
        if (size == 0){
            throw new ArrayIndexOutOfBoundsException();
        }
        return head.val;
    }

    public boolean isEmpty(){
        return size == 0;
    }

    public int size(){
        return size;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[");
        for (Node cur = head; cur != null; cur = cur.next){
            stringBuilder.append(cur.val);
            if (cur.next != null){
                stringBuilder.append(",");
            }
        }
        stringBuilder.append("]");
        return stringBuilder.toString();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值