为CircularQueue实现偏移方法的入队

时间:2015-11-03 21:53:07

标签: c++ data-structures queue circular-list

我目前正在开发一个模拟环形交叉口周围交通流的项目,为了做到这一点,我已经构建了2个数据结构“LinearQueue”和“CircularQueue”,它们都是使用Linked List结构节点实现的。

我的CircularQueue类具有排队和出列的方法,这是任何循环队列类型结构的典型方法,但是因为我有4个(实际上两个方向都有8条道路)LinearQueue对象需要以四分之一的容量间隔链接CircularQueue(roundabout)对象我需要一种方法来排队从队列后面或前面偏移的项目,我不确定如何正确实现它。

这是我的CircularQueue :: enqueue(Type)方法:

Type enqueue(Type& item) {

    // if the currentSize is greater than the maximum allowed capacity,
    // throw a CircularQueueException
    if (this->currentSize == this->maxCapacity) {
        throw CircularQueueException("Circular queue is full, cannot enqueue any more objects!");
    }

    // if the front of this CQ object is null, assign first element of circularQueue array to 
    // front of queue and set the rear to the front (single-element queue)
    if (this->front == 0) {
        this->front = this->circularQueue[0];
        this->front->head = item;
        this->rear = this->front;
    }

    // else if the front is not-null, assign the tail of the rear of this CQ object
    // to a new CQNode with head = item, and shift the new rear to tail of old rear
    else {
        this->rear->tail = new CQNode(item);

        this->rear = this->rear->tail;

        // if the currentSize of the queue is 1 less than the maximum capacity, then
        // point to tail of the rear to the front of the queue
        if (this->currentSize == (this->maxCapacity - 1))
            this->rear->tail = this->front;

    }

    // increment the currentSize of this CircularQueue instance by 1 indicating enqueue successful
    this->currentSize++;

    return item;

}

其中currentSize和maxCapacity是整数字段变量,分别存储当前填充的队列大小和最大允许容量。前后是指向以下节点结构的指针:

struct CQNode {
    Type head;
    CQNode* tail;

    CQNode() {
        //this->head = 0;
        this->tail = 0;
    }

    CQNode(Type& head, CQNode* tail = 0) {
        this->head = head;
        this->tail = tail;
    }

};

Type是类的模板中给出的类型名称。

我目前只有以下的偏移入队方法:

Type enqueue(Type& item, int offset) {

    // if the offset given is 0, then simply call overloaded enqueue with just the item
    if (offset == 0) {
        return enqueue(item);
    }

    Type* itemPtr = &item;

    if (itemPtr == 0) {
        throw std::invalid_argument("Item to be enqueued onto Circular Queue cannot be null!");
    }

    if (this->currentSize == this->maxCapacity) {
        throw CircularQueueException("Circular queue is full, cannot enqueue any more items.");
    }

}

我只是在努力寻找从这个方法开始的地方,因为我可以通过在我的CircularQueue中将不同偏移处的对象排队并出列队列来查看空指针的大量问题。

0 个答案:

没有答案