본문 바로가기
Algorithm/BOJ

[백준/BOJ] 10828번 - 스택 (C++)

by shine-jung 2022. 3. 25.
반응형

문제 링크


코드

#include <bits/stdc++.h>
using namespace std;

int main(void) {
    ios::sync_with_stdio(0);
    cin.tie(0);
    string s;
    stack<int> ST;
    int n, x;
    cin >> n;
    while (n--) {
        cin >> s;
        if (s == "push") {
            cin >> x;
            ST.push(x);
        }
        else if (s == "pop") {
            if (ST.empty()) cout << -1;
            else {
                cout << ST.top();
                ST.pop();
            }
            cout << '\n';
        }
        else if (s == "size") {
            cout << ST.size() << '\n';
        }
        else if (s == "empty") {
            cout << ST.empty() << '\n';
        }
        else if (s == "top") {
            if (ST.empty()) cout << -1;
            else cout << ST.top();
            cout << '\n';
        }
    }
}



설명


스택을 구현하는 문제이다.

STL 스택을 사용할 수도 있지만, 직접 구현해보면 더 좋다.




(주의) 기록용으로 작성한 글입니다. 좋은 코드가 아닐 수 있습니다.

댓글 환영합니다!


반응형

댓글