码迷,mamicode.com
首页 > 编程语言 > 详细

堆栈-数组实现

时间:2015-04-14 21:32:25      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

#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...\n");  
        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...\n");  
        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...\n");  
        return 0;  
    }  
    *data=ps->data[ps->top];  
    ps->top--;  
    return 1;  
}  

DataType top_stack(pstack ps)  
{  
    if(empty_stack(ps))  
    {  
        printf("Stack is empty...\n");  
        return 0;  
    }  
    return ps->data[ps->top];  
}  

void display(pstack ps)  
{  
    int i;  
    if(empty_stack(ps))  
    {  
        printf("Stack is empty...\n");  
        return;  
    }  
    printf("printf the items of stack...\n");  
    for(i=ps->top;i>-1;i--)  
        printf("%d ", ps->data[i]);  
    printf("\n");  
}
 
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\n", top_stack(ps));  
    for(i=0;i<num;i++)  
    {  
        pop(ps, &pdata);  
        printf("pop : %d\n", pdata);
    }  
    display(ps); 
    printf("end stack\n");   
    return 0;
}  

 

堆栈-数组实现

标签:

原文地址:http://www.cnblogs.com/xiangcool/p/4426112.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!