데이터를 저장하고 사용하는 하나의 방식이다.
모든 데이터의 저장과 삭제는 맨위 한쪽에서만 이루어지는 구조
스택에서 호출하는 명령어
4.size ; 스택에 있는 정수갯수 출력
5.empty : 스택이 비어있는지 확인하는 함수
#include <stdio.h>
#define maxsize 10000
#include <string.h>
int stack[maxsize];
int top=-1;
스택의 max사이즈는 10000, top=-1;
void push(int value){
if(top<-1){
top = -1;
}
else{top = top +1;
stack[top] = value;
}}
스택에 값넣는 함수 push
- top값을 1증가시킨뒤에 값 넣는다.
- 만약에 스택이 비어있을 경우 -1 출력.
void pop(void){
if (top<0){
printf("-1\n");
}
else {printf("%d\n",stack[top]);
top = top-1;
}
}
스택의 top자리(젤위)에 있는 데이터를 꺼내 출력하고, top을 1 감소시킨다. (감소시켜서 데이터가 삭제됨)
- 만약 스택이 비어있으면 -1출력
void top_print(void){
if(top<0){
printf("-1\n");
}
else{
printf("%d\n",stack[top]);
}
}
스택의 가장 위에있는 값 출력하는 함수 top
- 만약 비어있으면 -1출력
void isempty(void){
if(top<0){
printf("1\n");
}
else{
printf("0\n");
}
}
스택이 비어있는지 비어있으면 1 출력 아니면 0 출력하는 empty함수
void sizestack(void){
if(top<0){
printf("0\n");
}
else{
printf("%d\n",top+1);
} }
스택에 들어있는 정수의 개수 구하는 size함수
int main(){
int n;
int x;
scanf("%d",&n);
char command[11];
for(int i=0;i<n;i++){
scanf("%s",command);
if (!strcmp("push",command)){
scanf("%d",&x);
push(x);
}
if (!strcmp("pop",command)){
pop();
}
if (!strcmp("size",command)){
sizestack();
}
if (!strcmp("empty",command)){
isempty();
}
if (!strcmp("top",command)){
top_print();
}
}
return 0;
}