数据结构--链栈

头文件

#ifndef _LKSTACK_H_
#define _LKSTACK_H_

#include <stdlib.h>

typedef int data_t;
typedef struct lk_stacke{
    data_t data;
    struct lk_stacke *next;
}lk_stack;

//创建头节点
lk_stack *create_lkstack();
//判空
int empty_lkstack(lk_stack *s);
//求节点长度
int len_lkstack(lk_stack *s);
//入栈
int in_lkstack(lk_stack *s,data_t data);
//出栈
int out_lkstack(lk_stack *s);
//打印
int show_lkstack(lk_stack *s);
//清空
int clear_lkstack(lk_stack *s);
//摧毁
int destory_lkstack(lk_stack **s);

#endif

功能代码

#include <stdio.h>
#include "lkstack.h"

//创建头节点
lk_stack *create_lkstack()
{
    lk_stack *s = (lk_stack *)malloc(sizeof(lk_stack));
    if(NULL == s)
        return NULL;
    s->next = NULL;
    return s;
}
//判空
int empty_lkstack(lk_stack *s)
{
    return s->next == NULL;
}
//求节点长度
int len_lkstack(lk_stack *s)
{
    int len = 0;
    lk_stack *p = s->next;
    while(p != NULL){
        len++;
        p = p->next;
    }
    return len;
}
//入栈
int in_lkstack(lk_stack *s,data_t data)
{
    lk_stack *p = (lk_stack *)malloc(sizeof(lk_stack));
    if(NULL == p)
    {
        printf("create is fail\n");
        return -1;
    }
    p->data = data;
    p->next = s->next;
    s->next = p;
    return 0;
}
//出栈
int out_lkstack(lk_stack *s)
{
    if(1 == empty_lkstack(s))
    {
        printf("s is empty\n");
        return 1;
    }
    lk_stack *p = s->next;
    data_t temp = p->data;
    s->next = p->next;
    free(p);
    return temp;
}
//打印
int show_lkstack(lk_stack *s)
{
    if(1 == empty_lkstack(s))
    {
        printf("s is empty\n");
        return 1;
    }
    lk_stack *p = s->next;
    while(p != NULL)
    {
        printf("%d ",p->data);
        p = p->next;
    }
    printf("\n");
    return 0;
}
//清空
int clear_lkstack(lk_stack *s)
{    
    int len = len_lkstack(s);
    while(len--)
    {
        out_lkstack(s);
    }
    return 0;
}
//摧毁
int destory_lkstack(lk_stack **s)
{
    if(1 != empty_lkstack(*s))
    {
        clear_lkstack(*s);
    }
    free(*s);
    *s = NULL;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值