- 자료 구조 스택을 구현하는 문제
- push - 스택에 정수를 넣어준다.
- pop - 스택 가장 위에 수를 빼주고, 출력하고, 스택이 비어있으면 -1을 출력한다.
- size - 스택에 들어있는 정수의 개수를 출력한다.
- empty - 스택이 비어있으면 1, 아니면 0을 출력한다.
- top - 스택 가장 위에 정수를 출력해주고, 스택이 비어있으면 -1을 출력한다.
- 가장 기본적으로 스택 자료구조에 대한 이해가 필요하다.
- 스택은 LIFO(Last In First Out) 의 구조를 가진 자료구조이다.
- C++ STL Stack 라이브러리를 이용하여 구현하다.
후입 선출 (LIFO)의 자료구조 Stack의 STL
<stack>
헤어파일 추가
#include <stack> stack<int> st;
st.push(n);
st에 n을 삽입
st.pop();
st 마지막에 들어간 원소 삭제 (return 없음)
st.top();
st 마지막에 들어간 원소 return
st.empty();
st가 비어있는지 true, false return
st.size();
st에 들어있는 원소 수 return
st.swap(st1)
st1의 원소를 st와 전환
clear하는 법 2가지 1. while(!st.empty()) st.pop(); 2. st = stack<int>();
stack<int> st;
void push() {
int t;
cin >> t;
st.push(t);
return;
}
int pop() {
if (st.empty()) {
return -1;
}
else {
int top = st.top();
st.pop();
return top;
}
}
int size() {
return st.size();
}
int empty() {
if (st.empty()) {
return 1;
}
else {
return 0;
}
}
int top() {
if (st.empty()) {
return -1;
}
else {
int top = st.top();
return top;
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
string commandExample[5] = {"push", "pop", "size", "empty", "top"};
int N;
cin >> N;
string com;
while (N--) {
cin >> com;
for (int i = 0; i < 5; i++) {
if (com == commandExample[i]) {
if (i == 0) {
push();
}
else if (i == 1) {
cout << pop() << '\n';
}
else if (i == 2) {
cout << size() << '\n';
}
else if (i == 3) {
cout << empty() << '\n';
}
else if (i == 4) {
cout << top() << '\n';
}
break;
}
}
}
return 0;
}