数据结构(2)-队列


队列结构的特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。

一、队列结构的分类

  • 普通对列结构(quene)
  • 双端对列结构(de-que)
  • 优先级队列结构(pri-que)

二、用Java实现普通队列结构

2.1、基于数组
public class Quene {
    private int size;//队列长度
    private int front;//队头索引
    private int rear;//队尾索引
    private int[] theQuene;//用数组构造队列结构
    private int items;//当前队列的元素数

    public Quene(int size){
        this.size = size;
        theQuene = new int[size];
        front = 0;
        rear = -1;
        items = 0;
    }

    //入队
    public void  insert(int value){
         if(rear == size - 1){
             //已经满队,另队尾为-1,从队头插入
            rear = -1;
         }
         theQuene[++rear] = value;
         items++;
    }

    //出队
    public int remove(){
        int temp = theQuene[front++];
        if(front == size){
            front = 0;
        }
        items--;
        return  temp;
    }

    //查看队头
    public int peek(){
        return theQuene[front];
    }

    //是否为空队
    public boolean isEmpty(){
        return (items == 0);
    }

    //是否为满队
    public boolean isFull(){
        return (items == size);
    }

    //对列当前元素数
    public int sizeOf(){
        return items;
    }
}
2.2、基于链表

public class LinkedListQuene<T> {
    //队列大小
    private int queneLength = 0;
    //队头
    private Node first;
    //队尾
    private Node last;

    //链表节点
    private class Node {
        //指向下一节点
        Node next;
        //节点携带的数据
        T value;
        private Node(T value) {
            this.value = value;
        }
    }

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


 
    public int depth() {
        return queneLength;
    }
  
    public int enquene(T value) {
        Node node = new Node(value);
        //分两种情况,空队列和非空队列
        if (isEmpty()) {
            first = node;
            last = node;
            queneLength++;
            return 1;
        } else {
             Node oldNode = last;
            oldNode.next = node;
            last = node;
            queneLength++;
            return 1;
        }
    }

 
    public T dequene() {
        if (isEmpty()) {
            return null;
        } else {
            T value = first.value;
            first = first.next;
            queneLength--;
            return value;
        }
    }
 
    public T peek() {
        if (isEmpty()) {
            return null;
        } else {
            return first.value;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BoringRong

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值