C语言栈的实现

#include<stdio.h>
#include<stdlib.h>
#define MAX 10

struct stack_data
{
    int stack_array[MAX];
    int top;
};

typedef struct stack_data Stack;

enum result_val{EMPTY_OK = 1000,EMPTY_NO,FULL_OK ,FULL_NO,PUSH_OK,PUSH_NO,POP_NO,POP_OK};

int create_stack(Stack ** pastack)
{
    *pastack = (Stack*)malloc(sizeof(Stack));
    if(NULL == *pastack)
    {
        printf("malloc error\n");
        exit(EXIT_FAILURE);
    }
}

int int_stack(Stack * pastack)
{
    pastack->top = -1;
}

int is_full(Stack * pastack)
{
    if(MAX - 1 == pastack->top)
    {
        return FULL_OK;
    }
    else
    {
        return FULL_NO;
    }
}

int is_empty(Stack * pastack)
{
    if(-1 == pastack->top)
    {
        return EMPTY_OK;
    }
    else
    {
        return EMPTY_NO;
    }
}

int push_stack(Stack * pastack,int num)
{
    if(FULL_OK == is_full(pastack))
    {
        printf("the stack is full\n");
        return PUSH_NO;
    }
    pastack->top++;
    pastack->stack_array[pastack->top] = num;
    return PUSH_OK;
}

int pop_stack(Stack * pastack )
{
    if(EMPTY_OK == is_empty(pastack))
    {
        printf("the stack is empty!\n");
        return POP_NO;
    }
    
    return pastack->stack_array[pastack->top--];
    
}

int main()
{
    Stack * pastack;
    int i;
    int num;
    
    create_stack(&pastack);
    int_stack(pastack);

    for(i = 0; i < 10; i++)
    {
        if(PUSH_NO == push_stack(pastack,i+1))
        {
            printf("PUSH error\n");
        }
        else
        {
            printf("PUSH ok !\n");
        }
    }

    for(i = 0; i < 10; i++)
    {
        num = pop_stack(pastack);
        if(POP_OK == num)
        {
            printf("POP ok !\n");
        }
        else
        {
            printf("%d\n",num);
        }
    }

    free(pastack);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值