Реализация метода Enqueue At Offset для CircularQueue

В настоящее время я работаю над проектом по моделированию потока трафика вокруг кольцевой развязки, и для этого я построил 2 структуры данных «LinearQueue» и «CircularQueue», которые реализованы с использованием структурных узлов Linked List.

Мой класс CircularQueue имеет методы для постановки в очередь и удаления из очереди, как это типично для любой структуры типа круговой очереди, однако, поскольку у меня есть 4 (ну 8 фактически заданные дороги, идущие в обоих направлениях) объектов LinearQueue, которые необходимо будет связывать с интервалами четверти емкости CircularQueue ( обходной) объект Мне требуется метод для постановки в очередь элементов со смещением от задней или передней части очереди, и я не уверен, как правильно это реализовать.

Вот мой метод 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 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.

1

Решение

Задача ещё не решена.

Другие решения

Других решений пока нет …