C언어 스택(Stacks in C) - 배열로 구현(The implementation with the array)
- LIFO(Last In First Out) 정책을 수행한다.
- 가장 최근에 들어간 데이터가 가장 먼저 나온다.
- 삽입 명령을 스택에서는 PUSH 라고 불리운다.
- 삭제 명령은 주로 POP이라고 불리운다.
1. 동작원리
(1) 새로운 데이터를 PUSH하면 TOP은 해당 데이터를 가르킨다.
(2) 데이터를 POP하면 TOP이 가르키고 있는 데이터를 반환하고, TOP은 이전 데이터를 가르킨다.
|
[ Fig. 1 ] process of the stack, site : introduction to algorithms 3/E |
2. 함수 설명
stack_empty( struct stack) : 스택이 비어있는지 확인한다.
push( struct stack *, int) : 스택에 데이터를 입력한다.
pop( struct stack *) : 스택으로부터 데이터를 가져온다.
3. 전체 소스 코드
#include <stdio.h>
#define MAX 10 typedef struct stack{ int top; int ar[MAX]; }STACK; int stack_empty( STACK); void push( STACK *, int); int pop( STACK *); int main( void) { STACK S; // initialize the top of the stack. S.top = -1; push( &S, 10); push( &S, 30); push( &S, 20); pop( &S); pop( &S); pop( &S); pop( &S); } /* stack_empty( STACK) this function examine whether the stack is empty. */ int stack_empty( STACK s) { if( s.top == -1) return 1; return 0; } /* push( STACK *, int) insert a data into the stack and the variable 'top' point the top of the stack. */ void push( STACK *s, int data) { s->ar[++s->top] = data; printf("PUSH : %d\n", data); } /* pop( STACK *) get a data from the stack and remove the data in the stack. */ int pop( STACK *s) { if( stack_empty( *s)) { printf("the stack is empty!\n"); return; } printf("POP : %d\n", s->ar[s->top]); return s->ar[s->top--]; }
|
4. 실행 결과
|
'프로그래밍 언어들 > 알고리즘' 카테고리의 다른 글
C언어 큐(Queues in C) - 배열로 구현(The implementation with the array) (0) | 2016.10.25 |
---|---|
C언어 스택(Stacks in C) - 연결리스트로 구현(The implementation with the linked lists) (0) | 2016.10.25 |
최소신장트리(Minimum Spanning Trees)프림(prim) 알고리즘 (0) | 2016.10.19 |
최소신장트리(Minimum Spanning Trees) 크루스칼(Kruskal) 알고리즘 (2) | 2016.10.19 |
벨먼-포드 알고리즘(Bellman-Ford algorithm) (1) | 2016.10.18 |