Stack : 무언가를 쌓는다는 의미를 갖는 자료구조, 후입선출 (LIFO)의 자료구조
push : stack에 한 개 원소를 저장
pop : stack로부터 한 개 원소를 취함
+) empty (stack이 비어있는지 원소를 빼낼 때 체크), full (stack이 가득 차 있는지 원소를 넣을 때 체크)를 판별하는 것도 필요함.
#include <stdio.h>
#include <string.h>
int num[10001];
int count = 0;
void push(int x){
num[count] = x;
count ++;
}
void pop(){
if (count != 0){
count --;
printf ("%d\n", num[count]);
}
else printf ("-1\n");
}
void size(){
printf ("%d\n", count);
}
void empty(){
if (count != 0) printf ("0\n");
else printf ("1\n");
}
void top(){
if (count != 0) printf ("%d\n", num[count-1]);
//count-1 은 배열의 특성
else printf ("-1\n");
}
int main(void) {
int n; //명령의 수
int x = 0;
char command[10];
scanf ("%d", &n);
for (int i=0; i<n; i++){
scanf ("%s", command);
if (strcmp (command, "push") == 0){
scanf ("%d", &x);
push(x);
}
else if (strcmp (command, "pop") == 0) pop();
else if (strcmp (command, "size") == 0) size();
else if (strcmp (command, "empty") == 0) empty();
else if (strcmp (command, "top") == 0) top();
}
return 0;
}