반응형

스택 개념 이해 확인을 위한
기본 문제이다
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
string s;
stack<int> st;
for(int tmp=0; tmp<n; tmp++)
{
cin >> s;
if(s == "push")
{
int x;
cin >> x;
st.push(x);
}
if(s == "pop")
{
if(st.size() == 0) cout << -1;
else
{
cout << st.top();
st.pop();
}
cout << "\n";
}
if(s == "size")
{
cout << st.size();
cout << "\n";
}
if(s == "empty")
{
if(st.size() == 0) cout << 1;
else cout << 0;
cout << "\n";
}
if(s == "top")
{
if(st.size() == 0) cout << -1;
else
{
cout << st.top();
}
cout << "\n";
}
}
return 0;
}
push X 의 입력을 구현하는 방식을 조금 고민했었는데
입력값이 "push"라면
그 때 X의 입력을 받는구조로 구현해주면 된다
반응형
'algorithm > 스택' 카테고리의 다른 글
| [algorithm] 백준 3986번 좋은 단어 (0) | 2026.01.25 |
|---|---|
| [algorithm] 백준 9012번 괄호 (0) | 2026.01.25 |
| [algorithm] 백준 4949번 균형잡힌 세상 (0) | 2026.01.25 |
| [algorithm] 백준 10773번 제로 (0) | 2026.01.12 |
