[10828]
이 문제는 스택의 구현원리를 묻는것 같다. 스택이란, 후입선출(LIFO) 특성을 가지고 있다.
가장 먼저들어간 정보가 마지막에 나오고, 반대로 가장 나중에 들어간 정보가 가장 처음에 나오게 된다.

#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
stack<int> s; //스택
int n; //횟수
cin >> n;
string cmd; //명령어
int result = 0; //각 명령어의 결과값
for (int i = 0; i < n; i++) {
cin >> cmd;
//1. push
if (cmd == "push") {
int num;
cin >> num;
s.push(num);
}
//2. pop ( size 가 0이면 -1,0이 아니면 top값을 출력후 pop)
else if (cmd == "pop") {
if (s.size() == 0) {
result = -1;
cout << result << endl;
}
else {
result = s.top();
cout << result << endl;
s.pop();
}
}
//3. size
else if (cmd == "size") {
cout << s.size() << endl;
}
//4. empty(size가 0이면 1, size가 0이 아니면 0)
else if (cmd == "empty") {
if (s.size() == 0) {
result = 1;
cout << result<< endl;
}
else {
result = 0;
cout << result<< endl;
}
}
//5. top(size가 0이면 -1, size가 0이 아니면 top)
else if (cmd == "top") {
if (s.size() == 0) {
result = -1;
cout << result << endl;
}
else {
result = s.top();
cout << result << endl;
}
}
}
return 0;
}
[10845]
위문제와 비슷하지만, 큐를 구현하는 문제이다.
먼저 큐는 선입선출(FIFO) 구조를 가지고 있다. 제일 먼저 넣은 데이터가 가장 먼저나오게 되며, 큐의 앞부분을 front, 뒤를 back이라고 한다!


- push X: 정수 X를 큐에 넣는 연산이다.
- pop: 큐에서 가장 앞에 있는 정수를 빼고, 그 수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
- size: 큐에 들어있는 정수의 개수를 출력한다.
- empty: 큐가 비어있으면 1, 아니면 0을 출력한다.
- front: 큐의 가장 앞에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
- back: 큐의 가장 뒤에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
#include <iostream>
#include <queue>
#include <string>
using namespace std;
int main() {
queue<int> q; //스택
int n; //횟수
cin >> n;
string cmd; //명령어
int result = 0; //각 명령어의 결과값
for (int i = 0; i < n; i++) {
cin >> cmd;
//1. push
if (cmd == "push") {
int num;
cin >> num;
q.push(num);
}
//2. pop ( size 가 0이면 -1,0이 아니면 top값을 출력후 pop)
else if (cmd == "pop") {
if (q.size() == 0) {
result = -1;
cout << result << endl;
}
else {
result = q.front();
cout << result << endl;
q.pop();
}
}
//3. size
else if (cmd == "size") {
cout << q.size() << endl;
}
//4. empty(size가 0이면 1, size가 0이 아니면 0)
else if (cmd == "empty") {
if (q.size() == 0) {
result = 1;
cout << result<< endl;
}
else {
result = 0;
cout << result<< endl;
}
}
//5. front(size가 0이면 -1, size가 0이 아니면 front)
else if (cmd == "front") {
if (q.size() == 0) {
result = -1;
cout << result << endl;
}
else {
result = q.front();
cout << result << endl;
}
}
//6. back(size가 0이라면 -1, size가 0이 아니라면 back)
else if (cmd == "back") {
if (q.size() == 0) {
result = -1;
cout << result << endl;
}
else {
result = q.back();
cout << result << endl;
}
}
}
return 0;
}