1 Queues
2 Queue Which of the following cases use similar structures? Cars lined up at a tollgate Cars on a 4-lane highway Customers at supermarket check-out counter Books on a book shelf Clients before ATM machine Pile of bath towels on linen closet shelf
3 Queue Is a linear data structure with removal of items at one end (front) and insertion of items at the opposite end (back) FIFO – first-in-first-out frontback
4 Queue Operations Enqueue(item) Insert item at back Dequeue() Remove item at front Clear() Make queue empty IsEmpty() Is queue empty? IsFull() Is queue full?
5 Queue Implementation (1)
6 Problem with Implementation (1) frontrear With frequent queueing and dequeing, end of array can be reached quickly. Can we somehow use the empty spaces?
7 Queue Implementation (2)
8 Suppose, currently, front = 5 rear = 9 For next values, front = (front + 1) mod MAX_SIZE = 6 Rear = (rear + 1) mod MAX_SIZE = 0 frontrear MAX_SIZE
9 queue.h (Declarations) #define MAX_SIZE 5 #define EMPTY -1 typedef char elemType; class Queue { public: Queue(); void enqueue(elemType item); elemType dequeue(); bool isEmpty(); bool isFull(); void clear(); void print();...
10 queue.h (Declarations)... private: elemType data[MAX_SIZE]; int front; int back; int count; // for isFull, isEmpty }; // Note ‘;’
11 Queue() (Constructor) Queue::Queue(){ front = 0; back = -1; count = 0; }
12 Enqueue() void Queue::enqueue(elemType item){ if (!isFull()){ back = (back + 1) % MAX_SIZE; data[back] = item; count++; }
13 Dequeue() elemType Queue::dequeue(){ int result = EMPTY; if (!isEmpty()){ result = data[front]; front = (front + 1) % MAX_SIZE; count--; } return result; }
14 Clear() void Queue::clear(){ front = 0; back = -1; count = 0; }
15 IsEmpty() bool Queue::isEmpty(){ return count == 0; }
16 Driver Program #include #include "queue.h" using namespace std; void showMenu(); int main(){ // Declare variables int choice; elemType item; Queue q; showMenu(); cin >> choice;...
17 Driver Program while (choice != 0){ switch (choice){ case 1: cout << "Enter item." << endl; cin >> item; q.enqueue(item); cout << "Queue Contents:"<< endl; q.print(); cout << endl; break; case 2: item = q.dequeue(); cout << item << " was dequeued." << endl;...
18 Driver Program cout << "Queue Contents:"<< endl; q.print(); cout << endl; break; case 3: q.clear(); cout << "Queue Contents:"<< endl; q.print(); cout << endl; } showMenu(); cin >> choice; } return 0; }
19 showMenu() Function void showMenu(){ cout << " \n" << "1. Enqueue\n" << "2. Dequeue\n" << "3. Clear\n" << "0. Quit\n" << " \n" << "Please enter your choice." << endl; }
20 Your Turn Write the code to implement Queue::print(), which displays the contents of a queue, from front to back. Hint: consider two cases 10 front rear MAX_SIZE frontrear