有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中的数据结构手动入队和出队

我有一个队列数据结构的手动实现,我正在尝试将数字1-10放入一个最大大小为10的队列中。我的队列应该看起来像1,2,3,4,5,6,7,8,9,10,但由于某种原因,它看起来像10,1,2,3,4,5,6,7,8,9。这是我的排队方法,我从后面添加每个元素:

public int enqueue(int n) { 
    //where n is the item we want to add 
    if(isFull()){ //checks to see if rear+1 % data.length == front
        System.out.println("Cannot add item, queue is currently full.");
        return n;
    }

    else if(isEmpty()){ //checks to see if the front = rear = -1
        front = rear = 0;
        rear+=1;
    }

    else{ //allows for cyclic array
        rear = (rear + 1) % data.length;
    }

    data[rear] = n; 
    size ++;
    return n;
}

此外,当我尝试从数组中取出所有数字,然后显示出列数字的乘积时,每次都应该将前面的元素出列,但是,出列数字的乘积在某种程度上是-10,并且我的出列数组看起来像:10,1,2,3,4,5,6,7,8。以下是我的出列方法:

public int dequeue() { //remove the object from the front of queue 
    if(front == -1 && rear == -1){ //need for the and condition?    
        System.out.println("Cannot dequeue, queue is currently empty!");
        return -1;
    }

    else if(front == rear){
        front = rear = -1;
        
    }

    else{
        front = (front + 1) % data.length;
    }

    size --;
    return 0;

}

我还收到一大堆“无法出列,队列当前为空!”和“队列当前为空!”我的控制台中的输出。我哪里出错了


共 (1) 个答案

  1. # 1 楼答案

    在排队中,您只需要存储值、增量和大小。在出列时,您只需要增加前端和减小大小

        private final int[] data = new int[10];
        private int size, front, rear;
    
        public int enqueue(int n) {
            if (size == data.length) {
                throw new RuntimeException("Queue is full.");
            }
            data[rear] = n;
            rear = (rear + 1) % data.length;
            size++;
            return n;
        }
    
        public int dequeue() {
            if (size == 0) {
                throw new RuntimeException("Queue is empty.");
            }
            int e = data[front];
            front = (front + 1) % data.length;
            size ;
            return e;
        }