백준 10828 - 스택

프로그래밍 이모저모/프로그래밍 2019. 8. 14. 22:44

스택은 쉽다. 접시를 쌓아놓은 것과 같으므로. First In, First Out의 좋은 예시이다. class를 이용하여 구현해보았다.

#include <iostream>
#include <string>

using namespace std;

class stak
{
public:
    int length = 0;
    int Arr[10000];
    void push(int num);
    int pop();
    int top();
    int size();
    int empty();
};

void stak::push(int num)
{
    stak::Arr[stak::length] = num;
    stak::length++;
}
int stak::pop()
{
    if (length == 0)
        return -1;
    int top = Arr[length - 1];
    length--;
    return top;
}
int stak::top()
{
    if (length == 0)
        return -1;
    return Arr[length-1];
}
int stak::size()
{
    return length;
}
int stak::empty()
{
    if (length == 0)
        return 1;
    else return 0;
}

int main()
{
    int TC;
    cin >> TC;
    stak stak;
    for (int tc = 0; tc < TC; tc++)
    {
        string cmd;
        cin >> cmd;
        if (cmd == "push")
        {
            int num;
            cin >> num;
            stak.push(num);
        }
        else
        {
            if (cmd == "pop")
            {
                cout << stak.pop() << endl;
            }
            if (cmd == "top")
            {
                cout << stak.top() << endl;
            }
            if (cmd == "empty")
            {
                cout << stak.empty() << endl;
            }
            if (cmd == "size")
            {
                cout << stak.size() << endl;
            }
        }
    }
    return 0;
}

'프로그래밍 이모저모 > 프로그래밍' 카테고리의 다른 글

백준 2750 - 수 정렬하기  (0) 2019.08.14
백준 1920 - 수 찾기  (0) 2019.08.14
백준 1149 - RGB거리  (0) 2019.08.13
백준 2003 - 수들의 합  (0) 2019.08.12
백준 1037 - 약수  (0) 2019.08.12