I’m having a hard time trying to implement this method since array subscripts in C++ start with zero. The method add one element to the queue. You can use f (front) and r (rear) pointers and a sequential list of size n. If you find that additional variables are needed fell free. Thanks.
Thats my try but I know its wrong:
void QueueAr::enqueue(const Object& x){ prov = (r % n) + 1; if(prov != f){ r = prov; queueArray[r] = x; if(f = -1){ f = 0 } }else{ //queue is full } }
How do I work with the pointers? If I start them pointing to NULL I cant use pointer arithmetic.
To implement a queue using plain arrays, just treat it circularly – so as soon as you run out of space in the array, wrap back around to 0. You’ll need to keep a record of front and rear, as you note. As an example (where X represents an item in the queue):
You just have to use modular arithmetic to wrap around. Of course, this is limited in size (once you run out of elements, you’d have to allocate more memory), but that’s just what you get when dealing with arrays.
Here’s some code as a start (I haven’t checked it at all):