https://www.acmicpc.net/problem/10828

Stack
stack은 LILO방식으로, 마지막에 입력된 것이 먼저 출력되는 구조이다.
스택 원소를 담을 배열과 해당 원소를 가리키는 top을 이용하여 구현이 가능하다. 초기 top값은 -1이고, push를 이용하여 원소를 추가할 때는 top을 하나 증가시키고 그 자리에 원소를 넣는다. pop연산시에는 top 인덱스에 해당하는 값을 출력한 후 top을 하나 감소한다.
2번의 풀이는 c언어로 작성한다고 생각하고 stl을 사용하지 않았다.
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
int main() {
int n;
cin >> n;
stack<int> s;
string cmd;
for(int i=0; i<n; i++) {
cin >> cmd;
if (cmd == "push") {
int i;
cin >> i;
s.push(i);
}
else if (cmd == "pop") {
if (!s.empty()) {
cout << s.top() << endl;
s.pop();
}
else {
cout << "-1" << endl;
}
}
else if (cmd == "size") {
cout << s.size() << endl;
}
else if (cmd == "empty") {
if (s.empty())
cout << "1" << endl;
else
cout << "0" << endl;
}
else if (cmd == "top") {
if (!s.empty()) {
cout << s.top() << endl;
}
else
cout << "-1" << endl;
}
}
}
#include <iostream>
using namespace std;
int s[10000]; //문제 조건에서 n<=10,000
int tp=-1;
bool isFull() {
if(tp>=10000)
return true;
else
return false;
}
int isEmpty() {
if(tp==-1)
return 1;
else
return 0;
}
void push() {
int i;
cin >> i;
if(!isFull())
s[++tp] = i;
//cout << s[tp] << endl;
}
int pop() {
if(!isEmpty()) {
return s[tp--];
}
else
return -1;
}
int size() {
return tp+1;
}
int top() {
if(tp != -1)
return s[tp];
else
return -1;
}
int main() {
int n;
string cmd;
cin >> n;
for(int i=0; i<n; i++) {
cin >> cmd;
if(cmd == "push")
push();
else if(cmd =="pop")
cout << pop() << endl;
else if(cmd == "size")
cout << size() << endl;
else if(cmd == "empty")
cout << isEmpty() << endl;
else if(cmd == "top")
cout << top() << endl;
}
}