본문 바로가기

코딩테스트 연습/Baekjoon

[Baekjoon]10828번 : 스택 (c++)

https://www.acmicpc.net/problem/10828

 

10828번: 스택

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net

스택의 push, pop, empty, size를 배열을 사용해서 구현했다.

 

 


코드

#include <iostream>
using namespace std;
#define SIZE 1000000
int stack[SIZE];
int top;

void init()
{
    for (int i = 0; i < SIZE; i++)
        stack[i] = -1;
    top = -1;
}
void push(int num)
{
    top++;
    stack[top] = num;
}
void pop()
{
    if (top >= 0)
    {
        cout << stack[top] << endl;
        stack[top] = -1;
        top--;
    }
    else
        cout << "-1" << endl;
}

void empty()
{
    if (stack[0] == -1)
        cout << "1" << endl;
    else
        cout << "0" << endl;
}
void size()
{
    int cnt = 0;
    for (int i = 0; i < SIZE; i++)
    {
        if (stack[i] == -1)
            break;
        cnt++;
    }
    cout << cnt << endl;
}
int main(void)
{

    int test;
    string input;
    int num;
    cin >> test;
    init();

    for (int i = 0; i < test; i++)
    {
        // getline(cin, input);
        cin >> input;

        if (input == "push")
        {
            cin >> num; //숫자 하나 더받기
            push(num);
        }
        else if (input == "pop")
        {
            pop();
        }
        else if (input == "top")
        {
            if (top == -1)
                cout << "-1" << endl;
            else
            {
                cout << stack[top] << endl;
            }
        }
        else if (input == "size")
        {
            size();
        }
        else if (input == "empty")
        {
            empty();
        }
    }

    return 0;
}