0
#include <iostream>
using namespace std;

const int queue_size = 1000;

class queue
{
   private:
      // array containing queue elements
      char data [queue_size];
      char *front,   // index of the front of the queue 
                   // indexes 1 before actual front element
          *rear;    // index of the rear element in the queue
   public:
      // constructor creates an empty queue
      queue ();
      // adds a new element to the rear of the queue
      void enqueue (char item);
      // removes and returns the element at the front of the queue
      char dequeue ();
      // returns true if the queue is empty
      bool empty ();
      // returns true if the queue is full
      bool full ();
      void print();
};

// constructor creates an empty queue
queue::queue ()
{
   front = data;
   rear = data;
}

// adds a new element to the rear of the queue
void queue::enqueue (char item)
{
     // if the queue is full, print error
     if (full ())
     {
        cout << "\n\nQueue: enqueue error";
        cout << "\nEnqueueing on a full queue";
     }
     else // OK to add an element
     {
        rear ++;
        *rear = item;
     }
}

// removes and returns the element at the front of the queue
char queue::dequeue ()
{
     // if the queue is empty, print error
     if (empty ())
     {
        cout << "\n\nQueue: dequeue error";
        cout << "\nDequeueing an empty queue";
        cout << "\nReturning a space";
        return ' ';
     }
     else // OK to remove an element
     {
         front ++;
         return *front;
     }
}
        
// returns true if the queue is empty
bool queue::empty ()
{
     return front == rear;
}
      
// returns true if the queue is full
bool queue::full ()
{
     return data + queue_size -1 == front;
}

void queue::print()
{
     char *mover,*last;
     if(front == rear)
       cout <<"empty";
     last = rear;
     if (mover == data+ queue_size-1)
           mover= data;
         else
           mover++;
     for(mover= front; mover <= last;mover++)
     {
        
         cout<< *mover <<" ";
         
     }
     
}

Can you help me with the print function, i dont know if that is the right code to print it with Wrap Around

2
Contributors
1
Reply
3
Views
9 Years
Discussion Span
Last Post by dougy83
0

i dont know if that is the right code to print it with Wrap Around

No. You will have to check for wrap-around every time the pointer is incremented (i.e. inside the loop).

You will also have to check for wrap-around in enqueue() and dequeue() or you will read/write past the end of data[].

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.