头文件
#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;
}