Java实现一个Queue(环形数组)

Queue队列应该满足先入先出的原则。这里使用数组实现。

public class MyQueue {
    int front=1;
    int rear=0;
    int MaxSize;
    int[] queue;
    public MyQueue(int MaxSize){
        this.queue=new int[MaxSize];
        this.MaxSize=MaxSize;
    }
    public boolean isEmpty(){
        if(rear+1==front){
            System.out.print("queue为空");
            return true;
        }else {
            System.out.print("queue不为空");
            return false;
        }
    }
    public boolean addQueue(int n){
        if((front)%MaxSize!=rear) {
            queue[front%MaxSize] = n;
            front++;
            return true;
        }else{
            System.out.print("队列满");
            return false;
        }
    }
    public boolean deleteQueue(){
        if(rear+1<front){
            rear++;
            System.out.print(queue[rear%MaxSize]+"出列");
            return true;
        }else {
            System.out.println("删除失败");
            return false;
        }
    }
}

这里的addQueue是入队。deleteQueue是出对。
测试代码

   public static void main(String[] args)  {
        MyQueue queue=new MyQueue(3);
        queue.addQueue(1);
        queue.addQueue(2);
        queue.deleteQueue();
        queue.addQueue(3);
        queue.deleteQueue();
    }

结果:1出列2出列

正确

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
队列(Queue)是一种先进先出(First In First Out,FIFO)的数据结构,其中最先进入的元素会被最先处理。在Java中,我们可以通过自己实现一个队列来更好地理解它的内部原理。 Java中的队列可以使用数组或链表来实现,这里我们选择链表实现队列。首先,我们定义一个Node类: class Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; } } 其中,data表示结点存储的数据,next表示链表中下一个结点的引用。 然后,我们定义一个Queue类,并定义一些基本操作方法: class Queue { Node head; Node tail; int size; public Queue() { this.head = null; this.tail = null; this.size = 0; } public boolean isEmpty() { return head == null; } public int size() { return size; } public int peek() { if (isEmpty()) { throw new NoSuchElementException("Queue is empty"); } return head.data; } public void add(int data) { Node newNode = new Node(data); if (tail != null) { tail.next = newNode; } tail = newNode; if (head == null) { head = newNode; } size++; } public int remove() { if (isEmpty()) { throw new NoSuchElementException("Queue is empty"); } int data = head.data; head = head.next; if (head == null) { tail = null; } size--; return data; } } 在队列中,head表示队首,tail表示队尾。size表示队列中元素的数量。isEmpty方法用于判断队列是否为空;size方法用于获取队列中元素的数量;peek方法用于返回队首元素的值,但不删除;add方法用于向队列中添加元素;remove方法用于删除队首元素,并返回其值。 在实现完毕Queue类后,我们可以使用以下代码来测试它: Queue q = new Queue(); q.add(1); q.add(2); q.add(3); System.out.println(q.peek()); // 输出1 System.out.println(q.size()); // 输出3 System.out.println(q.remove()); // 输出1 System.out.println(q.peek()); // 输出2 System.out.println(q.size()); // 输出2 以上就是一个简单的Java队列的实现方法。通过实现一个队列,我们可以更好地理解队列的原理,进而更好地应用于实际开发中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值