循环队列数组插入案例

时间:2013-10-24 22:36:55

标签: java queue circular-list

我有实现这个非常接近完成的代码,导致我的IndexOutofBounds错误似乎是在插入队列的一种情况下发生的。有任何想法吗?在我的课程开始时,我将后部和前部设置为-1,计数为0.数组的最大大小为100.有一个isfull类可以测试计数是否为最大大小。

    public boolean insert(int n){

    if (isFull()){
        //not inserted
        return false;
    }
    else{

       //make it the first in queue if queue is empty
       if ( front == -1 && rear == -1){
           front++;
           rear++;
           list[front] = n;
           list[rear] = n;
           count++;
           return true;

       }
       //not at end of queue, add to end
        else if ( (count+1) <= 100 ){
            rear++;
            list[rear] = n;
            count++;
            return true;
        }
        //else add to front
        else{
            //update rear
            rear = ((count+1)%100)-1;
            list[rear] = n;
            return true;
        }
    }
}   

此代码到目前为止按此顺序在数组中插入一个数字: 0.检查是否已满。如果它退出。 1.如果队列为空,请将其作为第一项。 2.如果队列不为空或已满,请检查阵列背面是否超过最大位置。如果没有,请将其添加到最后。 3.如果队列不为空或已满,但队列后面已满。循环并将其插入数组的开头。

问题出在例如: - 数组填充数字1-100。此时阵列已满。 - 移除前面,然后阵列从2-100开始,第一个插槽为空。 - 插入刚刚删除的号码,这会导致错误。此时,计数+ 1不会超过最大点,因此它会尝试将其添加到后面。但由于最后一个点已满,它不会循环,抛出数组超出边界异常。我可以添加什么来检查最后一个点是否已填满并在这种情况下添加到数组的开头?

我的删除方法:

    public int remove(){
    //if empty return -1
    if (isEmpty()){
        return -1;
    }
    else{//else remove
        front++;
        int x = list[front-1];
        count--;
        return x;
    }
   }

1 个答案:

答案 0 :(得分:0)

public boolean insert(int n){

    if (isFull()){
        //not inserted
        return false;
    }
    else{

       //make it the first in queue if queue is empty
       if (isEmpty()){ //use empty
           front=0;//just set it 
           rear=0;//just set it 
       }
       list[rear] = n;
       rear = (rear+1)%100; //just rewind it when it reaches 100 index 0 must be free at this point

       count++;
       return true;
    }

}

我认为count是元素的数量,因此删除应该count--。在这种情况下,count总是<100;因为在你检查完之后阵列没有充满...所以你唯一要做的就是倒回后计数器;

另外删除应该front = (front+1)%100;

public int remove(){
    if (isEmpty()){
        return -1;
    }
    else{//else remove

        int x = list[front];//reorder
        front = (front+1)%100;//rewind
        count--;
        return x;
    }
}

empty()full()应使用计数

front指向remove()下一个

的元素

last总是指向下一个免费地点(或front也是下一个免费地点)