Guest User

Untitled

a guest
Jul 21st, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. class Queue{
  4. int front;
  5. int rear;
  6. int size;
  7. int *arr;
  8. public:
  9. // declare the member functions
  10. Queue(const int size);
  11. ~Queue();
  12. void enqueue(const int elem);
  13. void dequeue();
  14. void display();
  15. };
  16.  
  17. // function definitions
  18.  
  19. // creates a queue with the given size
  20. Queue::Queue(const int size){
  21. Queue::size = size;
  22. front = -1;
  23. rear = -1;
  24. arr = new int[size];
  25. }
  26.  
  27. Queue::~Queue(){
  28. delete [] arr;
  29. }
  30.  
  31. // adds an element to the queue
  32. void Queue::enqueue(const int elem){
  33. // if the queue is full then return beacuse we have an overflow
  34. if(front == 0 and rear == size - 1){
  35. std::cout << "QUEUE OVERFLOW!\n";
  36. return;
  37. }
  38.  
  39. // else add the element to the queue
  40. if(front < 0) front++;
  41. rear++;
  42. arr[rear] = elem;
  43. }
  44.  
  45. void Queue::dequeue(){
  46. // if the queue is empty then return because we have an underflow
  47. if(front == -1 and rear == -1){
  48. std::cout << "QUEUE UNDERFLOW!\n";
  49. return;
  50. }
  51. // else decrement rear by one
  52. rear--;
  53. // if rear is less than front then there are no elements present and we set both to -1
  54. if(rear < front){
  55. rear = -1;
  56. front = -1;
  57. }
  58. }
  59.  
  60. void Queue::display(){
  61. // if queue is empty then return because there is nothing to display
  62. if(front == -1 && rear == -1){
  63. return;
  64. }
  65.  
  66. // else print from the front to rear
  67. for(int i = front; i <= rear; i++){
  68. std::cout << arr[i] << " ";
  69. }
  70. std::cout << "\n";
  71. }
  72.  
  73. int main(int argc, char const *argv[]) {
  74. Queue queue(5);
  75. queue.enqueue(10);
  76. queue.enqueue(20);
  77. queue.enqueue(30);
  78. queue.enqueue(40);
  79. queue.enqueue(50);
  80. queue.display();
  81. queue.dequeue();
  82. queue.display();
  83. return 0;
  84. }
Add Comment
Please, Sign In to add comment