#include <bits/stdc++.h>
using namespace std;
int n, num;
string order; // 문자열 변수 생성
stack<int>ps; // 스택 STL
int main() {
cin.tie(0);
ios_base::sync_with_stdio(0);
cin >> n;
for (int i = 0; i < n; i++) {
cin >> order;
if (order == "push") {
cin >> num;
ps.push(num);
} // push 명령
else if (order == "pop") {
if (!ps.empty()) {
cout << ps.top() << endl;
ps.pop();
}
else
cout << "-1" << endl;
} // pop 명령
else if (order == "size") {
cout << ps.size() << endl;
} // size 명령
else if (order == "empty") {
if (ps.empty()) {
cout << "1" << endl;
}
else
cout << "0" << endl;
} // empty 명령
else if (order == "top") {
if (!ps.empty()) {
cout << ps.top() << endl;
}
else
cout << "-1" << endl;
} // top 명령
}
return 0;
}
<aside> 💡 참고할 점
</aside>
#include <bits/stdc++.h>
using namespace std;
int t, n;
string sentence;
stack<char>rev; // 자료형이 char인 스택 선언
int main() {
cin.tie(0);
ios_base::sync_with_stdio(0);
cin >> t;
cin.ignore();
// 입력 버퍼 초기화 : 개행문자를 그대로 남겨두는 것을 초기화해줌(개행문자 : 줄바꿈, 스페이스 등)
for (int i = 0; i < t; i++) {
sentence = "";
getline(cin, sentence); // 구분자를 만날 때 까지 모든 문자열을 입력 받아 하나의 string 객체에 저장
sentence += ' '; // 구분자 따로 입력
for (int j = 0; j < sentence.size(); j++) {
if (sentence[j] == ' ') { // 띄어쓰기 공백이 있을 때
while (!rev.empty())
{
cout << rev.top();
rev.pop();
} // 비어있지 않을 때까지 스택에서 제거
cout << sentence[j]; // 문장의 각 단어를 거꾸로 한 문자열 출력
}
else rev.push(sentence[j]); // 문장의 각 단어를 거꾸로 한 문자열 출력
}
cout << "\\n"; // 줄 바꿈 처리
}
return 0;
}
<aside> 💡 참고할 점
</aside>
cin.ignore() : 입력 버퍼를 초기화해주는 함수 (공백, 줄 바꿈 처리)
getline(cin, 데이터 이름) : 구분자를 만날 때 까지 모든 문자열을 입력 받아 하나의 string 객체에 저장
cf) i am happy → i, am, happy
데이터명.size() : 데이터의 크기를 나타내 줌
stack 은 선입 후출로서 먼저 들어간 데이터는 가장 마지막에 나오게 되는 구조이다.
→ 문제