C++)
#include <iostream>
#include <stack>
#include <algorithm>
#define endl "\n"
using namespace std;
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
string str;
stack<int> s;
while(n--) {
cin >> str;
switch(str.at(0)) {
case 'p':
if(str.at(1) == 'u')
{
string temp;
cin >> temp;
s.push(stoi(temp));
}
else
{
if(!s.empty())
{
cout << s.top() << endl;
s.pop();
}
else
cout << -1 << endl;
}
break;
case 's':
cout << s.size() << endl;
break;
case 'e':
int isEmpty = (s.empty()) ? 1 : 0;
cout << isEmpty << endl;
break;
case 't':
if(!s.empty()) cout << s.top() << endl;
else cout << -1 << endl;
break;
}
}
return 0;
}
Python)
import sys
read = sys.stdin.readline
n = int(read().rstrip())
st = []
for _ in range(n):
ord = read().rstrip().split()
if ord[0] == 'push':
st.append(int(ord[-1]))
elif ord[0] == 'top':
print(st[-1] if st else -1)
elif ord[0] == 'pop':
temp = -1
if st:
temp = st[-1]
st.pop()
print(temp)
elif ord[0] == 'size':
print(int(len(st)))
else:
print(0 if st else 1)'백준 1 > 자료구조' 카테고리의 다른 글
| [백준 1158] 요세푸스 문제 (C++/Python) (0) | 2020.12.06 |
|---|---|
| [백준 2161] 카드1 (C++/Python) (0) | 2020.12.06 |
| [백준 10845] 큐 (C++/Python) (0) | 2020.12.06 |
| [백준 9012] 괄호 (C++/Python) (0) | 2020.12.06 |
| [백준 10773] 제로 (C++/Python) (0) | 2020.12.06 |