#include <iostream>
#include <vector>
#include<sstream>
#include <algorithm>
#include <string>
#include <utility>
#include <stack>
using namespace std;
int main() {
stack<int> s;
int N;
cin >> N;
for (int i = 0; i < N; i++) {
string command;
int num;
cin >> command;
if (command == "push") {
cin >> num;
s.push(num);
}
else if (command == "pop") {
if (s.empty()) {
cout << -1 << endl;
}
else {
cout << s.top() << endl;
s.pop();
}
}
else if (command == "size") {
cout<<s.size() << endl;
}
else if (command == "empty") {
if (s.empty()) {
cout << 1 << endl;
}
else {
cout << 0 << endl;
}
}
else if (command == "top") {
if (s.empty()) {
cout << -1 << endl;
}
else {
cout << s.top() << endl;
}
}
}
}
스위치문으로 바꾸면 시간이 줄어들 줄 알았는데 줄지 않았다.
#include <iostream>
#include <vector>
#include<sstream>
#include <algorithm>
#include <string>
#include <utility>
#include <stack>
using namespace std;
int main() {
enum MyEnum
{
PUSH, POP, SIZE, EMPTY, TOP
};
stack<int> s;
int N;
cin >> N;
for (int i = 0; i < N; i++) {
string command;
cin >> command;
int commandNum;
if (command == "push")
commandNum = PUSH;
else if (command == "pop")
commandNum = POP;
else if (command == "size")
commandNum = SIZE;
else if (command == "empty")
commandNum = EMPTY;
else if (command == "top")
commandNum = TOP;
switch (commandNum)
{
case PUSH:
int num;
cin >> num;
s.push(num);
break;
case POP:
if (s.empty()) {
cout << -1 << endl;
}
else {
cout << s.top() << endl;
s.pop();
}
break;
case SIZE:
cout << s.size() << endl;
break;
case EMPTY:
if (s.empty()) {
cout << 1 << endl;
}
else {
cout << 0 << endl;
}
break;
case TOP:
if (s.empty()) {
cout << -1 << endl;
}
else {
cout << s.top() << endl;
}
break;
default:
break;
}
}
}