스택-배열 구현

7652 단어 배열
#include <stdio.h>  

#include <malloc.h>    

#define DataType int  

#define MAX 1024 

 

typedef struct  

{  

    DataType data[MAX];  

    int top;  

}stack, *pstack; 

 

pstack init_stack()  

{  

    pstack ps;  

    ps=(pstack)malloc(sizeof(stack));  

    if(!ps)  

    {  

        printf("Error. fail malloc...
"); return NULL; } ps->top=-1; return ps; } int empty_stack(pstack ps) { if(-1 == ps->top) return 1; else return 0; } int push(pstack ps, DataType data) { if(ps->top == MAX-1) { printf("Stack is full...
"); return 0; } ps->top++; ps->data[ps->top]=data; return 1; } int pop(pstack ps, DataType *data) { if(empty_stack(ps)) { printf("Stack is empty...
"); return 0; } *data=ps->data[ps->top]; ps->top--; return 1; } DataType top_stack(pstack ps) { if(empty_stack(ps)) { printf("Stack is empty...
"); return 0; } return ps->data[ps->top]; } void display(pstack ps) { int i; if(empty_stack(ps)) { printf("Stack is empty...
"); return; } printf("printf the items of stack...
"); for(i=ps->top;i>-1;i--) printf("%d ", ps->data[i]); printf("
"); } int main() { int i, num, data, pdata; pstack ps; ps=init_stack(); printf("Enter stack num:"); scanf("%d", &num); for(i=0;i<num;i++) { scanf("%d", &data); push(ps, data); } display(ps); printf("Top is %d
", top_stack(ps)); for(i=0;i<num;i++) { pop(ps, &pdata); printf("pop : %d
", pdata); } display(ps); printf("end stack
"); return 0; }

좋은 웹페이지 즐겨찾기