은근한

실력키우기 - 자료처리 [stack] 본문

ALGORITHM/Data Structure

실력키우기 - 자료처리 [stack]

EsJoo 2016. 1. 18. 03:12

스택이란?

스택(stack)은 제한적으로 접근할 수 있는 나열 구조이다. 그 접근 방법은 언제나 목록의 끝에서만 일어난다. 

끝먼저내기 목록(Pushdown list)이라고도 한다.

스택은 한 쪽 끝에서만 자료를 넣거나 뺄 수 있는 선형 구조(LIFO - Last In First Out)으로 되어 있다.

자료를 넣는 것을 '밀어넣는다' 하여 푸시(push)라고 하고 반대로 넣어둔 자료를 꺼내는 것을 팝(pop)이라고 하는데, 

이때 꺼내지는 자료는 가장 최근에 보관한 자료부터 나오게 된다. 

이처럼 나중에 넣은 값이 먼저 나오는 것을 LIFO 구조라고 한다.





#include <stdio.h>
#include <stdlib.h>
 
typedef struct _node{
    int value;
    struct _node *next;
}node;
 
typedef node* nptr;
 
typedef struct _stack{
    int count;
    nptr top;
}stack;
 
void push(stack *sptr,int data);
int pop(stack *sptr);
void init(stack *sptr);
int get_stack_count(stack *sptr);
void print(int *res,int index);
int main(int argc, const char * argv[]) {
    
    int n;    
    char select;
    int data;
    int *res;
    int index=0;
    
    stack *st = (stack *)malloc(sizeof(stack));
    init(st);
    scanf("%d",&n);
    res = (int *)malloc(sizeof(int*)*n);
        
    while (n>=1&&n<=100) {
        scanf("%c",&select);
        
        if(select=='i'){
            scanf("%d",&data);
            push(st, data);
            n—;
        } else if (select=='c'){
            res[index] = get_stack_count(st);
            //printf("%d",res[index]);
            index = index+1;
 
            n—;
        } else if (select=='o'){
            res[index] = pop(st);
            //printf("%d",res[index]);
            index = index+1;
            n—;            
        }        
    }    
 
    print(res,index);
    
    return 0;
}
 
void print(int *res,int index){
    int i;
    for (i=0; i<index; i++) {
        if (res[i]>=0) {
            printf("%d\n",res[i]);
        } else {
            printf("empty\n");
        }
    }
}
 
void init(stack *sptr){
    sptr->count = 0;
    sptr->top = NULL;
}
 
void push(stack *sptr,int data){
    
    nptr new_node = (nptr)malloc(sizeof(node));
    new_node->value = data;
    new_node->next = sptr->top;
    sptr->top = new_node;
    sptr->count = sptr->count+1
}
 
 
int pop(stack *sptr){
    int val;
 
    if(sptr->count>0){
        nptr tmp = sptr->top;
        sptr->top = tmp->next;
        val = tmp->value;
        free(tmp);
        sptr->count = sptr->count-1;
        return val;
    }
    else {
        return -1;
    }
}
int get_stack_count(stack *sptr){
    return sptr->count;
}
cs