Search
moon
sun
📗

스택

주차
문제번호
10828
언어
C++
티어
실버
유형
구현
자료구조
스택
nj_Blog
nj_상태
이해도
100%
풀이
사람
이해도 2
13 more properties

문제접근🤔

•
stack 자료구조를 사용
•
stringstream 사용하여 명령어와 정수를 구분

놓쳤던 부분😅

•
cin은 공백을 입력 받을 수 없음
•
cin과 getline을 함께 이용하게 되면 cin에서 \n을 입력 받기 때문에 getline의 기본 구분자가 \n라서 바로 종료됨. 따라서 cin.ignore()필요
•
stringstream을 사용할때 clear를 사용하지 않아 for문이 한번 끝날때마다 eofbit 1이 켜지기 때문에 clear를 통해서 eofbit를 초기화 해야함

코드😁

2212 KB

4 ms

#include <iostream> #include <stack> #include <string> #include <sstream> using namespace std; int main(void) { int n; stack<int> s; stringstream stream; string op; string input; int element; ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n; cin.ignore(); for (int i = 0; i < n; i++) { getline(cin, input); stream.clear(); stream.str(input); stream >> op >> element; if (op == "push") s.push(element); else if (op == "pop") { if (s.empty()) cout << "-1\n"; else { cout << s.top() << "\n"; s.pop(); } } else if (op == "size") cout << s.size() << "\n"; else if (op == "empty") { if (s.empty()) cout << "1\n"; else cout << "0\n"; } else { if (s.empty()) cout << "-1\n"; else cout << s.top() << "\n"; } } return (0); }
C++
복사