CS/C++

C++로 스택/큐 구현하기

munsik22 2025. 4. 12. 20:45

스택

#include <iostream>
#define MAX 100

class Stack {
private:
    int arr[MAX];
    int top;

public:
    Stack() {
        top = -1;
    }

    void push(int x) {
        if (top >= MAX - 1) {
            return;
        }
        arr[++top] = x;
    }

    // 스택에서 요소 제거
    int pop() {
        if (isEmpty()) {
            return -1;
        }
        return arr[top--];
    }

    int peek() {
        if (isEmpty()) {
            return -1;
        }
        return arr[top];
    }

    bool isEmpty() {
        return top == -1;
    }

    int size() {
        return top + 1;
    }
};

int main() {
    Stack s;

    s.push(10);
    s.push(20);
    s.push(30);

    std::cout << "Stack Top: " << s.peek() << std::endl;

    std::cout << s.pop() << "was popped." << std::endl;
    std::cout << "Stack Top: " << s.peek() << std::endl;

    std::cout << "Stack Size: " << s.size() << std::endl;

    return 0;
}

#include <iostream>
#define MAX 100

class Queue {
private:
    int arr[MAX];
    int front;
    int rear;

public:
    Queue() {
        front = -1;
        rear = -1;
    }

    void enqueue(int x) {
        if (rear >= MAX - 1) {
            return;
        }
        if (front == -1)
            front = 0;
        arr[++rear] = x;
    }

    int dequeue() {
        if (isEmpty()) {
            return -1;
        }
        return arr[front++];
    }

    int peek() {
        if (isEmpty()) {
            return -1;
        }
        return arr[front];
    }

    bool isEmpty() {
        return front == -1 || front > rear;
    }

    int size() {
        if (isEmpty()) {
            return 0;
        }
        return rear - front + 1;
    }
};

int main() {
    Queue q;

    q.enqueue(10);
    q.enqueue(20);
    q.enqueue(30);

    std::cout << "Queue Front: " << q.peek() << std::endl;

    std::cout << q.dequeue() << "was dequeued." << std::endl;
    std::cout << "Queue Front: " << q.peek() << std::endl;

    std::cout << "Queue Size: " << q.size() << std::endl;

    return 0;
}

'CS > C++' 카테고리의 다른 글

C++로 이진 탐색 트리 구현하기  (0) 2025.04.15
C++로 TIC TAC TOE 게임 구현하기  (0) 2025.04.15
C++로 연결 리스트 구현하기  (0) 2025.04.08
C++ 기초 정리  (0) 2025.03.30