Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #define MAX_SIZE 32 // 스택의 최대 사이즈
- typedef int element; // 스택에 넣을 자료의 자료형 element (여기서는 int)
- // 고정 크기 스택 FixedStack 구조체 선언
- typedef struct _FixedStack
- {
- element arr[MAX_SIZE]; // MAX_SIZE크기 스택 배열
- int top; // 스택 top 요소의 인덱스
- } FixedStack;
- // 스택 초기화 함수
- void stack_init(FixedStack* s)
- {
- s.top = -1; // 빈 스택 = top 인덱스 변수를 -1일때로 하자.
- }
- // 스택이 비었다면 1, 비어있지 않다면 0을 리턴
- int stack_is_empty(FixedStack* s) { return (s->top == -1); }
- // 스택이 꽉 찼다면 1, 꽉 차지않았다면 0을 리턴
- int stack_is_full(FixedStack* s) { return (s->top == MAX_SIZE - 1); }
- // 스택 s에 새 요소 e를 삽입
- void stack_push(FixedStack* s, element e)
- {
- // 스택이 꽉 찼다면 삽입할 수 없습니다
- if (stack_is_full(s))
- {
- printf("Stack is full!\n");
- return;
- }
- // 스택에 여유자리가 있으면 삽입
- else
- {
- ++s->top; // 현재 top 요소의 다음 인덱스에다가
- s->arr[s->top] = e; // 삽입할 요소 e 삽입!
- }
- }
- // 스택 s로부터 요소를 pop
- element stack_pop(FixedStack* s)
- {
- // 스택이 비어있다면 요소를 제거할 수 없음. 비어있지 않을 때만 동작
- if (!stack_is_empty(s))
- {
- element pop = s->arr[s->top]; // top 요소를 임시저장
- --s->top; // top 인덱스를 하나 감소
- return pop; // 임시저장한 top 요소를 리턴
- }
- }
- // 스택의 최상단 요소 읽기
- element stack_peek(FixedStack* s) { return s->arr[s->top]; }
- // 스택 출력
- void stack_print(FixedStack* s)
- {
- printf("< Stack >\n");
- if (stack_is_empty(s))
- printf("-- Empty stack --\n");
- else
- {
- // top ~ 0 인덱스까지 반복문으로 출력
- for (int i = s->top; i >= 0; --i)
- printf(" [ %2d ]\n", s->arr[i]);
- }
- printf("\n");
- }
- int main()
- {
- FixedStack s;
- stack_init(&s);
- stack_print(&s);
- stack_push(&s, 10);
- stack_push(&s, 20);
- stack_push(&s, 30);
- stack_push(&s, 40);
- stack_print(&s);
- stack_pop(&s);
- stack_pop(&s);
- stack_print(&s);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement