数据结构三 队列

队列介绍

队列是一个有序列表,可以用数组或是链表来实现。
遵循先入先出的原则。即:先存入队列的数据,要先取出。后存入的要后取出

注意:
这里队列的front是指第一个元素的前一个元素,而rear则是直接指向最后一个元素,这里只是单纯这样规定而已,就好比链表有的设了头指针,有的没有设头指针
实现代码:

public class Test1 {

    public static void main(String[] args) {
    MyQueue myQueue=new MyQueue(4);
    myQueue.addQueue(1);
    myQueue.addQueue(2);
    myQueue.addQueue(3);
    myQueue.addQueue(4);
    myQueue.addQueue(5);
    System.out.println("首元素为: "+myQueue.headQueue());
    System.out.println("出队元素为:"+myQueue.OutQueue());
    System.out.println("出队元素为"+myQueue.OutQueue());
    myQueue.allQueue();
    }
}
class MyQueue {
    private int maxSize;
    //front和rear有所区别,front指向的是第一个元素的上一个位置,而rear则是直接指向最后一个元素
    private int front;
    private int rear;
    private int[] a;

    //使用构造器初始化队列
    public MyQueue(int maxSize) {
        this.maxSize = maxSize;
        front = -1;
        rear = -1;
        a = new int[maxSize];
    }

    public boolean isEmpty()
    {
        //当front与rear相等时,因为被front指向的元素必然已经出队列了,所以此时为空
        return front==rear;
    }
    public boolean isFull()
    {
        //当rear指向最大索引时,表示此时队列已满
        return rear==maxSize-1;
    }
    //令元素进入队列
    public void addQueue(int x)
    {
        if(isFull())
        {
            System.out.println("队列已满,不能再继续添加元素了");
            return;
        }
        rear++;
        a[rear]=x;
    }
    //令元素出队列
    public int OutQueue()
    {
        if(isEmpty())
        {
           throw new RuntimeException("队列为空,没有数据能够出队");
        }
        front++;
        return a[front];
    }
    //显示头部队列元素的数据
    public int headQueue()
    {
        if(isEmpty())
        {
            throw new RuntimeException("队列为空,没有数据能够出队");
        }
        return a[front+1];
    }
    //显示队列所有元素
    public void allQueue()
    {
       if(isEmpty())
       {
           System.out.println("队列为空,没有数据能够出队");
           return;
       }
        System.out.println("队列所有元素为:");
       for(int i=front+1;i<=rear;++i)
       {
           System.out.print(a[i]+"\t");
       }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值