Created
October 5, 2013 15:34
-
-
Save flyfire/6842352 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef QUEUE_H | |
#define QUEUE_H | |
#include <stdexcept> | |
template <typename T> | |
class Queue { | |
static const int MAX_SIZE = 100; | |
int head, tail; | |
T queue[MAX_SIZE]; | |
int back(const int &x) const { return (x == MAX_SIZE - 1) ? 0 : x + 1; } | |
bool is_full() const { return back(tail) == head; } | |
public: | |
Queue(): head(0), tail(0) {} | |
bool is_empty() const { return head == tail; } | |
bool enqueue(const T &item); | |
T dequeue(); | |
T get_head() const; | |
T get_tail() const; | |
}; | |
template <typename T> | |
bool Queue<T>::enqueue(const T &item) { | |
if (is_full()) { | |
return false; | |
} | |
tail = back(tail); | |
queue[tail] = item; | |
return true; | |
} | |
template <typename T> | |
T Queue<T>::dequeue() { | |
if (is_empty()) { | |
throw std::underflow_error("queue is empty"); | |
} | |
int called_head = head; | |
head = back(head); | |
return queue[called_head]; | |
} | |
template <typename T> | |
T Queue<T>::get_head() const { | |
if (is_empty()) { | |
throw std::underflow_error("queue is empty"); | |
} | |
return queue[head]; | |
} | |
template <typename T> | |
T Queue<T>::get_tail() const { | |
if (is_empty()) { | |
throw std::underflow_error("queue is empty"); | |
} | |
return queue[tail - 1]; | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment