Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- class Queue{
- int front;
- int rear;
- int size;
- int *arr;
- public:
- // declare the member functions
- Queue(const int size);
- ~Queue();
- void enqueue(const int elem);
- void dequeue();
- void display();
- };
- // function definitions
- // creates a queue with the given size
- Queue::Queue(const int size){
- Queue::size = size;
- front = -1;
- rear = -1;
- arr = new int[size];
- }
- Queue::~Queue(){
- delete [] arr;
- }
- // adds an element to the queue
- void Queue::enqueue(const int elem){
- // if the queue is full then return beacuse we have an overflow
- if(front == 0 and rear == size - 1){
- std::cout << "QUEUE OVERFLOW!\n";
- return;
- }
- // else add the element to the queue
- if(front < 0) front++;
- rear++;
- arr[rear] = elem;
- }
- void Queue::dequeue(){
- // if the queue is empty then return because we have an underflow
- if(front == -1 and rear == -1){
- std::cout << "QUEUE UNDERFLOW!\n";
- return;
- }
- // else decrement rear by one
- rear--;
- // if rear is less than front then there are no elements present and we set both to -1
- if(rear < front){
- rear = -1;
- front = -1;
- }
- }
- void Queue::display(){
- // if queue is empty then return because there is nothing to display
- if(front == -1 && rear == -1){
- return;
- }
- // else print from the front to rear
- for(int i = front; i <= rear; i++){
- std::cout << arr[i] << " ";
- }
- std::cout << "\n";
- }
- int main(int argc, char const *argv[]) {
- Queue queue(5);
- queue.enqueue(10);
- queue.enqueue(20);
- queue.enqueue(30);
- queue.enqueue(40);
- queue.enqueue(50);
- queue.display();
- queue.dequeue();
- queue.display();
- return 0;
- }
Add Comment
Please, Sign In to add comment