kar7mp5

[자료 구조] C++ built-in array로 Queue 구현 본문

전공/자료구조

[자료 구조] C++ built-in array로 Queue 구현

kar7mp5 2024. 3. 29. 12:45
728x90
#include <iostream>

using namespace std;

class arrayQueue
{
public:
    arrayQueue(int capacity);
    bool empty();
    int size();
    bool full();
    void front();
    void rear();
    void enqueue(int data);
    void dequeue();

private:
    int *arr;
    int capacity;
    int frontIndex;
    int rearIndex;
    int n;
};

arrayQueue::arrayQueue(int capacity)
{
    this->capacity = capacity;
    arr = new int[capacity];
    frontIndex = rearIndex = 0;
    n = 0;
}

bool arrayQueue::empty()
{
    return (n == 0);
}

int arrayQueue::size()
{
    return n;
}

bool arrayQueue::full()
{
    if (size() == capacity)
    {
        return true;
    }
    else
    {
        return false;
    }
}

void arrayQueue::front()
{
    if (empty())
    {
        cout << "Empty" << endl;
        return;
    }
    else
    {
        cout << arr[frontIndex] << endl;
    }
}

void arrayQueue::rear()
{
    if (empty())
    {
        cout << "Empty" << endl;
    }
    else
    {
        if (rearIndex == 0)
        {
            cout << arr[capacity - 1] << endl;
        }
        else
        {
            cout << arr[rearIndex - 1] << endl;
        }
    }
}

void arrayQueue::enqueue(int data)
{
    if (size() == capacity)
    {
        cout << "Full" << endl;
        return;
    }
    arr[rearIndex] = data;
    rearIndex = (rearIndex + 1) % capacity;
    n++;
}

void arrayQueue::dequeue()
{
    if (empty())
    {
        cout << "Empty" << endl;
        return;
    }
    else
    {
        cout << arr[frontIndex] << endl;
        frontIndex = (frontIndex + 1) % capacity;
        n--;
    }
}

int main()
{
    int N;
    int T;

    cin >> N >> T;

    arrayQueue *q = new arrayQueue(N);

    string s;

    while (T--)
    {
        cin >> s;

        if (s == "enqueue")
        {
            int value;
            cin >> value;
            q->enqueue(value);
        }
        else if (s == "dequeue")
        {
            q->dequeue();
        }
        else if (s == "isEmpty")
        {
            if (q->empty())
            {
                cout << "True" << endl;
            }
            else
            {
                cout << "False" << endl;
            }
        }
        else if (s == "size")
        {
            cout << q->size() << endl;
        }
        else if (s == "front")
        {
            q->front();
        }
        else if (s == "rear")
        {
            q->rear();
        }
        else if (s == "full")
        {
            if (q->full())
            {
                cout << "True" << endl;
            }
            else
            {
                cout << "False" << endl;
            }
        }
    }

    return 0;
}
728x90