Leetcode - 622. Design Circular Queue

숲사람·2022년 9월 25일
0

멘타트 훈련

목록 보기
154/237

문제

아래와 같이 동작하는 Circular Queue를 구현하라.

MyCircularQueue(k) Initializes the object with the size of the queue to be k.
int Front() Gets the front item from the queue. If the queue is empty, return -1.
int Rear() Gets the last item from the queue. If the queue is empty, return -1.
boolean enQueue(int value) Inserts an element into the circular queue. Return true if the operation is successful.
boolean deQueue() Deletes an element from the circular queue. Return true if the operation is successful.
boolean isEmpty() Checks whether the circular queue is empty or not.
boolean isFull() Checks whether the circular queue is full or not.

해결

배열사이즈는 +1. enqueue할때 rear를 먼저 증가시키고 rear위치에 삽입. front값은 front 인덱스를 1증가 시킨 위치.
이전에 작성한 C구현 참고 -> [C] Circular Queue 구현

class MyCircularQueue {
    vector<int> arr;
    int size;
    int front;
    int rear;
    
public:
    MyCircularQueue(int k) {
        size = k + 1;
        arr = vector<int>(size, 0);
        front = 0;
        rear = 0;
    }
    
    /*
    f
    o o 2 5
          r     
    */
    bool enQueue(int value) {
        if (isFull())
            return false;
        /* insert it after increasing rear */
        rear = (rear + 1) % size;
        arr[rear] = value;
        return true;
    }
    
    bool deQueue() {
        if (isEmpty())
            return false;
        front = (front + 1) % size;
        return true;
    }
    
    int Front() {
        if (isEmpty())
            return -1;
        return arr[(front + 1) % size];
    }
    
    int Rear() {
        if (isEmpty())
            return -1;
        return arr[rear];
    }
    
    /*
    f  // empty f == r
    o o o o
    r
    */
    bool isEmpty() {
        if (front == rear)
            return true;
        return false;
    }
    
    /*  full: f == (r+1) % size
      f
    o 2 5 3
    r     
    */
    bool isFull() {
        if (front == (rear + 1) % size)
            return true;
        return false;
    }
};
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글