c언어(알고리즘)

스택(Stacks) - 배열로 구현(The implementation with the array)

Happy_Dobi 2016. 11. 1. 16:24

1. 스택

   - 후입선출(Last-In-First-Out(LIFO)) 원리의 자료구조이다.

   - 한 쪽 끝에서만 자료를 넣거나 뺄 수 있는 선형구조로 되어있다. 


2. stack 함수

   - int stackpop(int *) : 스택에서 top이 가리키는 요소를 꺼내는 함수

   - void stackpush(int *,int) : 스택에 요소를 삽입하는 함수

   - int stackempty(int) : 스택이 비어있는지 검사 하는 함수


3. 소스 

  1. #include<stdio.h>
  2.  
  3. int stackpop(int *);  // 스택에서 top이 가리키는 요소를 꺼내는 함수
  4. void stackpush(int *,int);  // 스택에 요소를 삽입하는 함수
  5. int stackempty(int);  // 스택이 비어있는지 검사 하는 함수
  6.  
  7. int top = -1;
  8.  
  9. int main(void)
  10. {
  11.     int arr[10] = {0,};
  12.    
  13.    
  14.     stackpush(arr,10);
  15.  
  16.    
  17.     printf("%d\n",stackpop(arr));
  18.  
  19.     stackpop(arr);
  20.  
  21.     return 0;
  22. }
  23.  
  24. int stackpop(int *arr)
  25. {
  26.     int data = 0;
  27.  
  28.     if(stackempty(top) < 0)  // top 의 위치를 검사하고 스택이 비어있으면 NULL을 반환한다.
  29.         return NULL;
  30.     else    // top의 위치를 검사하고 데이터가있으면 스택의 가장 위의 데이터가 반환된다.
  31.     {
  32.         printf("pop -> ");
  33.         data = (*(arr+(top--)));   
  34.         return data;
  35.     }
  36. }
  37.  
  38. void stackpush(int * arr, int data) // 스택에 데이터를 삽입하는 함수
  39. {
  40.     printf("push -> %d\n",data);
  41.     (*(arr+(++top))) = data;
  42. }
  43.  
  44. int stackempty(int top)     // top위치를 검사해 스택의 상태를 반환한다.
  45. {
  46.     if(top < 0)
  47.     {
  48.         printf("Stack empty\n");
  49.         return -1;
  50.     }
  51.     else
  52.         return 1;
  53. }


4. 결과