백준 10828 : 스택
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])
Author And Source
이 문제에 관하여(백준 10828 : 스택), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@imchanyang/백준-10828-스택저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)