-
[Python][C++] 10828번 스택Algorithm/Baekjoon 2024. 6. 29. 14:44
문제
https://www.acmicpc.net/problem/10828
코드
1. Python
import sys input = sys.stdin.readline n = int(input()) arr = [] for _ in range(n): cmd = input().rstrip() if cmd[:4] == "push": cmd, i = cmd.split() arr.append(i) elif cmd == "pop": if len(arr): print(arr.pop()) else: print(-1) elif cmd == "size": print(len(arr)) elif cmd == "empty": if len(arr): print(0) else: print(1) elif cmd == "top": if len(arr): print(arr[-1]) else: print(-1)
2. C++
#include <iostream> #include <stack> #include <string> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; stack<int> s; string command; int num; while (n--) { cin >> command; if (command == "push") { cin >> num; s.push(num); } else if (command == "pop") { if (s.empty()) cout << "-1\n"; else { cout << s.top() << "\n"; s.pop(); } } else if (command == "size") cout << s.size() << "\n"; else if (command == "empty") cout << (s.empty() ? 1 : 0) << "\n"; else if (command == "top") cout << (s.empty() ? -1 : s.top()) << "\n"; } return 0; }
풀이
문제에서 요구한대로 스택을 구현하는 간단한 문제
C++에서 구현할 때, 다양하게 연습하기 위해 중간에 삼항연산자를 사용했지만 일관된 코드 블록 스타일을 사용하는 것이 더 좋다.
'Algorithm > Baekjoon' 카테고리의 다른 글
[Python][C++] 11650번 좌표 정렬하기 (0) 2024.06.30 [Python][C++] 10845번 큐 (0) 2024.06.29 [Python][C++] 10816번 숫자 카드 2 (0) 2024.06.28 [Python][C++] 10814번 나이순 정렬 (0) 2024.06.27 [Python][C++] 10773번 제로 (0) 2024.06.27