【栈】用数组

#include <stdio.h>
#include <stdlib.h>

#define MAX 10

enum return_val {FULL_OK, FULL_NO, EMPTY_OK, EMPTY_NO, PUSH_OK, PUSH_NO, POP_OK, POP_NO, GET_OK, GET_NO};

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

typedef struct stack_data Stack;

void create_stack(Stack ** stack)
{
    *stack = (Stack*)malloc(sizeof(Stack));

    if(*stack == NULL)
    {
        printf("malloc error!\n");
        exit(-1);
    }
}

void init_stack(Stack *stack)
{
    stack->top = -1;
}

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

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

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

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

int gettop_stack(Stack *stack,int *num)
{
    if(is_empty(stack) == EMPTY_OK)
    {
        printf("stack is empty!\n");
        return GET_NO;
    }
    else
    {
        *num = stack->stack_array[stack->top];
        return GET_OK;
    }
}

void empty_stack(Stack *stack)
{
    stack->top = -1;
}

int main()
{
    Stack * stack;
    int i;
    int num;

    create_stack(&stack);

    init_stack(stack);

    for(i = 0; i < MAX + 2; i++)
    {
        if(push_stack(stack,i + 1) == PUSH_OK)
        {
            printf("push ok!num is %d\n",i + 1);
        }
        else
        {
            printf("push no!\n");
        }
    }

    for(i = 0; i < MAX - 2; i++)
    {
        if(pop_stack(stack,&num) == POP_NO)
        {
            printf("pop no!\n");
        }
        else
        {
            printf("stack is %d\n",num);
        }
    }

    empty_stack(stack);    //加上和去掉分别看看

    for(i = 0; i < 3; i++)
    {
        if(gettop_stack(stack,&num) == GET_NO)
        {
            printf("top is empty!\n");
        }
        else
        {
            printf("top is %d\n",num);
            pop_stack(stack,&num);
        }
    }
    
    return 0;
 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值