백준 10828 : 스택(C++, Python)

Chanyang Im·2021년 7월 21일
0

BAEKJOON

목록 보기
3/13
post-thumbnail

10828 스택

문제

풀이

이 문제는 스택을 구현하는 기본적인 문제입니다.

C++ STL인 stack의 기초적인 사용법을 알아야합니다.

Python에서는 stack을 리스트로 구현합니다.
또한 input()을 쓰면 시간초과가 되므로
sys.stdin.readline()를 써야합니다.

C++ 코드

#include <iostream>
#include <stack>
#include <string>

using namespace std;

int main() {
 
    int N;
    cin >> N;
    
    stack<int> S;
    
    while(N--) {
        string M;
        cin >> M;
        
        if(M == "push") {
            int dt;
            cin >> dt;
            S.push(dt);
        }
        else if(M == "pop") {
            if(S.empty()) {
                cout << -1 << endl;
            }
            else {
                cout << S.top() << endl;
                S.pop();
            }
        }
        else if(M == "size") {
            cout << S.size() << endl;
        }
        else if(M == "empty") {
            cout << S.empty() << endl;
        }
        else if(M == "top") {
            if(S.empty()) {
                cout << -1 << endl;
            }
            else {
                cout << S.top() << endl;
            }
        }
    }
    return 0;
}

Python 코드

import sys

S = []

N = int(sys.stdin.readline())

for i in range(N):
    command = sys.stdin.readline().split()

    if command[0] == "push":
        dt = command[1]
        S.append(dt)
    elif command[0] == "pop":
        if len(S) == 0:
            print(-1)
        else:
            print(S.pop())
    elif command[0] == "size":
        print(len(S))
    elif command[0] == "empty":
        if len(S) == 0:
            print(1)
        else:
            print(0)
    elif command[0] == "top":
        if len(S) == 0:
            print(-1)
        else:
            print(S[-1])

profile
안녕하세요!! 세상에 관심이 많은 공학자입니다!😆

0개의 댓글