|
| 1 | +/*** |
| 2 | + * _ __ ___ _ |
| 3 | + * | |/ /___ ___ _ __ / __|__ _| |_ __ |
| 4 | + * | ' </ -_) -_) '_ \ | (__/ _` | | ' \ |
| 5 | + * |_|\_\___\___| .__/ \___\__,_|_|_|_|_| |
| 6 | + * |_| |
| 7 | + * _ |
| 8 | + * __ _ _ _ __| | |
| 9 | + * / _` | ' \/ _` | |
| 10 | + * \__,_|_||_\__,_| |
| 11 | + * |
| 12 | + * _ _ _ _ _ _ |
| 13 | + * | | ___ __ _ _ _ _ _ /_\ | |__ _ ___ _ _(_) |_| |_ _ __ ___ |
| 14 | + * | |__/ -_) _` | '_| ' \ / _ \| / _` / _ \ '_| | _| ' \| ' \(_-< |
| 15 | + * |____\___\__,_|_| |_||_| /_/ \_\_\__, \___/_| |_|\__|_||_|_|_|_/__/ |
| 16 | + * |___/ |
| 17 | + * Yeah! Ravi let's do it! |
| 18 | + */ |
| 19 | + |
| 20 | +#ifndef QUEUE_H |
| 21 | +#define QUEUE_H |
| 22 | + |
| 23 | +#include <exception> |
| 24 | + |
| 25 | +namespace algo { |
| 26 | + const int defaultQueueCapacity = 500; |
| 27 | + |
| 28 | + template <typename T> |
| 29 | + class Queue { |
| 30 | + public: |
| 31 | + Queue( int capacity = defaultQueueCapacity ) |
| 32 | + : _capacity { capacity }, _count { 0 }, |
| 33 | + _head { 0 }, _tail { -1 }, _elements { new T[_capacity] } |
| 34 | + { |
| 35 | + } |
| 36 | + |
| 37 | + bool empty() const |
| 38 | + { |
| 39 | + return ( _count == 0 ); |
| 40 | + } |
| 41 | + |
| 42 | + int count() const |
| 43 | + { |
| 44 | + return _count; |
| 45 | + } |
| 46 | + |
| 47 | + int capacity() const |
| 48 | + { |
| 49 | + return _capacity; |
| 50 | + } |
| 51 | + |
| 52 | + void pop() |
| 53 | + { |
| 54 | + if (empty()) |
| 55 | + { |
| 56 | + return; |
| 57 | + } |
| 58 | + else { |
| 59 | + --_count; |
| 60 | + ++_head; |
| 61 | + if ( _head == _capacity ) { |
| 62 | + _head = 0; |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + bool push( const T & obj ) |
| 68 | + { |
| 69 | + if ( _count == _capacity ) { |
| 70 | + return false; |
| 71 | + } |
| 72 | + else { |
| 73 | + ++_count; |
| 74 | + ++_tail; |
| 75 | + if ( _tail == _capacity ) |
| 76 | + { |
| 77 | + _tail = 0; |
| 78 | + } |
| 79 | + _elements[_tail] = obj; |
| 80 | + return true; |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + const T & front() const |
| 85 | + { |
| 86 | + if ( empty() ) throw empty_queue_exception; |
| 87 | + return _elements[_head]; |
| 88 | + } |
| 89 | + |
| 90 | + private: |
| 91 | + class EmptyQueueException : public std::exception { |
| 92 | + virtual const char * what() const throw() |
| 93 | + { |
| 94 | + return "Queue is empty"; |
| 95 | + } |
| 96 | + } empty_queue_exception; |
| 97 | + |
| 98 | + int _capacity; |
| 99 | + int _count; |
| 100 | + int _head; |
| 101 | + int _tail; |
| 102 | + |
| 103 | + T * _elements; |
| 104 | + |
| 105 | + Queue( const Queue & ); |
| 106 | + Queue & operator= ( const Queue & ); |
| 107 | + |
| 108 | + }; //end of class queue |
| 109 | + |
| 110 | +} //end of namespace algo |
| 111 | + |
| 112 | +#endif //end of QUEUE_H |
0 commit comments