jtentor icon

DemoQueue3 - SpecialQueue.h

jtentor | PRO | 05/17/20 03:49:11 PM UTC | 0 ⭐ | 1018 👁️ | Never ⏰ | []
C++ |

2.36 KB

|

None

|

0 👍

/

0 👎

//
// Created by Julio Tentor <[email protected]>
//
 
#ifndef DEMOQUEUE3_SPECIALQUEUE_H
#define DEMOQUEUE3_SPECIALQUEUE_H
 
template <class ELEMENT>
class specialqueue {
public:
    specialqueue(int capacity = 10);
    virtual ~specialqueue();
    void push(const ELEMENT & element);
    ELEMENT front();
    void pop();
    const int size();
    specialqueue<ELEMENT> join(specialqueue<ELEMENT> & other);
 
private:
    int capacity;
    ELEMENT * data;
    int head;
    int tail;
    int count;
    int next(int position);
};
 
template <class ELEMENT>
specialqueue<ELEMENT>::specialqueue(int capacity) {
    this->capacity = capacity;
    this->data = new ELEMENT[this->capacity];
    this->head = 0;
    this->tail = 0;
    this->count = 0;
}
 
template <class ELEMENT>
specialqueue<ELEMENT>::~specialqueue() {
    delete [] this->data;
}
 
template <class ELEMENT>
const int specialqueue<ELEMENT>::size() {
    return this->count;
}
 
template<class ELEMENT>
int specialqueue<ELEMENT>::next(int position) {
    return (++position >= this->capacity)? 0: position;
}
 
template<class ELEMENT>
void specialqueue<ELEMENT>::push(const ELEMENT &element) {
    if (this->count >= this->capacity) {
        throw std::runtime_error("ERROR La cola esta llena...");
    }
    this->data[this->tail] = element;
    this->tail = this->next(this->tail);
    ++this->count;
}
 
template<class ELEMENT>
ELEMENT specialqueue<ELEMENT>::front() {
    if (this->count <= 0) {
        throw std::runtime_error("ERROR La cola esta vacía...");
    }
    return this->data[this->head];
}
 
template<class ELEMENT>
void specialqueue<ELEMENT>::pop() {
    if (this->count <= 0) {
        throw std::runtime_error("ERROR La cola esta vacía...");
    }
    this->head = this->next(this->head);
    --this->count;
}
 
template<class ELEMENT>
specialqueue<ELEMENT> specialqueue<ELEMENT>::join(specialqueue<ELEMENT> & other) {
    specialqueue<ELEMENT> result = specialqueue<ELEMENT>((this->size() + other.size()) * 2);
    for(int pos = this->head, c = this->size(); c > 0; --c) {
        result.push(this->data[pos]);
        pos = this->next(pos);
    }
    for(int pos = other.head, c = other.size(); c > 0; --c) {
        result.push(other.data[pos]);
        pos = other.next(pos);
    }
 
    return result;
}
 
#endif //DEMOQUEUE3_SPECIALQUEUE_H

Comments