用java类实现循环队列

本程序意在使用java类(初学)实现循环队列

具体原理请参考数据结构:队列


这里是方法

package pga;

public class MyQueue {

    int MaxSize = 5;
    private int[] date;
    private int front;
    private int rear;

    public void GetFront(){
        if(isEmpty())
            System.out.println("This queue has no front");
        else System.out.println(date[front]);
    }

    public boolean isFull(){
        return (rear + 1) % MaxSize == front;
    }

    public boolean isEmpty(){
        return front == rear;
    }

    public void InitQueue()
    {
        date = new int[MaxSize];
        front = rear = 0;
    }

    public boolean EnQueue(int e)
    {
        if (isFull()) {
            System.out.println("This queue is full");
            return false;
        }
        date[rear] = e;
        rear = (rear + 1) % MaxSize;
        return true;
    }

    public boolean DeQueue()
    {
        if (isEmpty()){
            System.out.println("This queue is empty");
            return false;
        }
        front = (front + 1) % MaxSize;
        return true;
    }
}

这里是主程序

package pga;

public class app {
    public static void main(String[] args){

        MyQueue Q = new MyQueue();
        Q.InitQueue();

        Q.GetFront();//此时队列中没有元素

        int[] list = {1, 2, 3, 4, 5};
        for(int i : list)
            Q.EnQueue(i);//前四个元素正常进队,录入第五个元素时队满

        Q.GetFront();

        Q.DeQueue();

        Q.GetFront();

        Q.DeQueue();
        Q.DeQueue();
        Q.DeQueue();//此时队空
        Q.DeQueue();

//        for(int i = 1;i <= 4;i++)
//            Q.DeQueue();

        Q.EnQueue(6);//测试循环队列是否正常
        Q.GetFront();

    }
}

注释已经写的很详细了,不做赘述。


下面是运行结果,请参考注释理解

来自石大ZJJ

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值