线性栈操作

栈是一种非常重要的数据结构,本文介绍了一些简单的栈的操作。

 

#include <stdio.h>

typedef struct STACK_NODE {    
    int *pData;	
    int length;	
    int top;
}stack_t;

/*初始化stack*/
stack_t *init_stack(int index)
{
    stack_t *stack = NULL;
    if (index == 0)
        return;
    stack = (stack_t *)malloc(sizeof(stack_t));
    if (stack == NULL) {
        stack = (stack_t *)malloc(sizeof(stack_t));
        if (stack == NULL)
            return NULL;
    }
    stack->pData = (int *)malloc(sizeof (int) * index);
    if (stack->pData == NULL) 
	{
         stack->pData = (int *)malloc(sizeof (int) * index);
         if (stack == NULL) {
            free(stack);
            return NULL;
         }
    }

    stack->length = index;
    stack->top = 0;
    return stack;
}

/*删除stack*/
void destory_stack(stack_t *stack)
{
    if (stack == NULL)

        return ;
    free(stack->pData);
    stack->pData = NULL;
    free(stack);
    stack = NULL;
    return ;
}

/*判断stack为空*/
int is_stack_empty(stack_t *stack)
{
    if (stack == NULL)
        return 1;
    if (stack->top == 0)
        return 0;
    else
        return 1;
}

/*判断stack为满*/
int is_stack_full(stack_t *stack)
{
    if (stack == NULL)
        return 1;
    if (stack->top == stack->length)
        return 0;
    else
        return 1;
}

/*入stack*/
int push_data_to_stack(stack_t *stack, int data)
{
    if (stack == NULL)
        return 1;
    if (!is_stack_full(stack))
        return 1;
    stack->pData[stack->top++] = data;
    
    return 0;
}

/*出stack*/
int pop_data_from_stack(stack_t *stack, int *data)
{
    if (stack == NULL)
        return 1;
    if (!is_stack_empty(stack))
        return 1;
    *data = stack->pData[--stack->top];
    return 0;
}

void print_stack_data(stack_t *stack)
{
    int i;

    if (!is_stack_empty(stack)) 
        return;
    for (i=0; i < stack->top;  i++) {
        printf ("%d\n",stack->pData[i]);
    }
}

/*测试用例*/
int main(int argc, char *argv[])
{
    int i;
    int index;
    stack_t *stack;

    stack = init_stack(10);
    for (i=0; i<10; i++) {
        if (push_data_to_stack(stack,i))
            printf("push data %d error\n", i);
    }
    print_stack_data(stack);

    for (i=0;i<10;i++) {
        if (pop_data_from_stack(stack,&index))
            printf ("poll data %d error\n", i);
        printf ("the index is %d\n", index);
        index = 0;
    }

    return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值