queue.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // queue.cpp -- Queue and Customer methods
  2. #include "queue.h"
  3. #include <cstdlib> // (or stdlib.h) for rand()
  4. // Queue methods
  5. Queue::Queue(int qs) : qsize(qs)
  6. {
  7. front = rear = NULL; // or nullptr
  8. items = 0;
  9. }
  10. Queue::~Queue()
  11. {
  12. Node * temp;
  13. while (front != NULL) // while queue is not yet empty
  14. {
  15. temp = front; // save address of front item
  16. front = front->next;// reset pointer to next item
  17. delete temp; // delete former front
  18. }
  19. }
  20. bool Queue::isempty() const
  21. {
  22. return items == 0;
  23. }
  24. bool Queue::isfull() const
  25. {
  26. return items == qsize;
  27. }
  28. int Queue::queuecount() const
  29. {
  30. return items;
  31. }
  32. // Add item to queue
  33. bool Queue::enqueue(const Item & item)
  34. {
  35. if (isfull())
  36. return false;
  37. Node * add = new Node; // create node
  38. // on failure, new throws std::bad_alloc exception
  39. add->item = item; // set node pointers
  40. add->next = NULL; // or nullptr;
  41. items++;
  42. if (front == NULL) // if queue is empty,
  43. front = add; // place item at front
  44. else
  45. rear->next = add; // else place at rear
  46. rear = add; // have rear point to new node
  47. return true;
  48. }
  49. // Place front item into item variable and remove from queue
  50. bool Queue::dequeue(Item & item)
  51. {
  52. if (front == NULL)
  53. return false;
  54. item = front->item; // set item to first item in queue
  55. items--;
  56. Node * temp = front; // save location of first item
  57. front = front->next; // reset front to next item
  58. delete temp; // delete former first item
  59. if (items == 0)
  60. rear = NULL;
  61. return true;
  62. }
  63. // customer method
  64. // when is the time at which the customer arrives
  65. // the arrival time is set to when and the processing
  66. // time set to a random value in the range 1 - 3
  67. void Customer::set(long when)
  68. {
  69. processtime = std::rand() % 3 + 1;
  70. arrive = when;
  71. }