Another ADT: Queues

Mar 22, 2024  β”‚  m. Mar 22, 2024 by Charlotte Curtis

This page provides lecture notes for an additional example of an abstract data type. Due to time constraints, I didn’t have time to present this during class, but it may help provide additional examples to clarify the concept of ADTs.

Queues

bg right:40% flavour

Queues in CS

bg right 80%

Characteristics

Queue operations

Like the stack ADT, we need to decide who is responsible for checking if the queue is full/empty. Providing functions for this delegates the responsibility to the client code

Other potential queue operations

Technically these are not standard queue operations, but priority queues

A queue of integers: interface

class IntQueue {
public:
    IntQueue();
    ~IntQueue();

    void enqueue(int item); // add an item to the tail
    int dequeue(); // remove an item from the head
    bool empty() const; // check if the queue is empty
private:
    ???
};

This assumes we are implementing an unbounded queue. What would change if we wanted a bounded queue?

A queue of integers: sample usage

IntQueue q;
int n;
source >> n;
while (!source.eof()) {
    q.enqueue(n);
    source >> n;
}

while (!q.empty()) {
    cout << q.dequeue() << ' ' << endl;
}

Assume source contains integers from 1 to 5. What is the output?

Usage challenge

Given a queue of integers as shown, replace the contents of the queue with the product of all the numbers

23510   ...

Approach:

  1. Dequeue the first two items
  2. Multiply them together
  3. Enqueue the result
  4. Repeat until the queue is empty

Queue implementation

Queue implementation using linked lists

class IntQueue {
public:
...
private:
    struct Node {
        int data;
        Node *next;
    };
    Node *head;
    Node *tail;
};

Queue: constructor/destructor and helpers

IntQueue::IntQueue() {
    head = NULL;
    tail = NULL;
}

IntQueue::~IntQueue() {
    while (!empty()) {
        dequeue();
    }
}
bool IntQueue::empty() const {
    return head == NULL;
}

int IntQueue::peek() const {
    if (empty())
        ???;
    return head->data;
}

Queue: enqueue and dequeue

void IntQueue::enqueue(int item) {
    Node *new_node = new Node;
    new_node->data = item;
    new_node->next = NULL;
    if (empty())
        head = new_node;
    else
        tail->next = new_node;
    
    tail = new_node;
}
int IntQueue::dequeue() {
    int result = head->data;
    Node *dying = head;
    head = head->next;
    delete dying;
    if (empty())
        tail = NULL;

    return result;
}


Previous: Midterm Trivia
Next: Troubleshooting INS Quota Issues