一.头文件sqstack.h的实现
#ifndef __SQSTACK_H__
#define __SQSTACK_H__
#include<stdio.h>
#include<stdlib.h>
typedef int datatype;
typedef struct
{
datatype *data;//这样写能制定认为输入栈大小
int maxlen;
int top;
}sqstack;
extern sqstack *stack_creat(int len);
extern int stack_empty(sqstack * s);
extern void stack_clear(sqstack *s);
extern int stack_full(sqstack * s);
extern int stack_push(sqstack *s,datatype value);
extern datatype stack_pop(sqstack *s);
extern datatype stack_top(sqstack *s);
extern void stack_free(sqstack *s);
#endif
二.函数实现sqstack.c的实现
#include "sqstack.h"
sqstack *stack_creat(int len)
{
sqstack *s;
if((s=(sqstack *)malloc(sizeof(sqstack))) == NULL)
{
printf("malloc failed\n");
return NULL;
}
if((s->data = (datatype *)malloc(sizeof(datatype))) == NULL)
{
printf("malloc failed\n");
return NULL;
}
s -> maxlen = len;
s -> top = -1;
return s;
}
/*
*@ret:1 empty
*/
int stack_empty(sqstack * s)
{
return (s->top == -1?1:0);
}
void stack_clear(sqstack *s)
{
s -> top = -1;
}
int stack_full(sqstack * s)
{
return (s -> top == s->maxlen - 1?1:0);
}
int stack_push(sqstack *s,datatype value)
{
if(s->top == s ->maxlen -1)
{
printf("stack is full\n");
return -1;
}
s->data[s->top+1] = value;
s->top++;
return 1;
}
datatype stack_pop(sqstack *s)
{
s->top--;
return s->data[s->top+1];
}
datatype stack_top(sqstack *s)
{
return (s->data[s->top]);
}
void stack_free(sqstack *s)
{
free(s->data);
s->data = NULL;
free(s);
s = NULL;
}
三.主函数test.c中实现
#include"sqstack.h"
int main()
{
int n = 10;
sqstack *s;
s = stack_creat(n);
stack_push(s,10);
stack_push(s,20);
stack_push(s,30);
stack_push(s,40);
stack_clear(s);
while(!stack_empty(s))
{
printf("%d ",stack_pop(s));
}
puts("");
stack_free(s);
return 0;
}
四.makefile的实现
CFLAGS=-c -Wall -g
test:sqstack.o test.o
.PHONY:clean
clean:
rm *.o test

本文介绍了如何使用C语言实现链式栈的数据结构,包括头文件`sqstack.h`的定义,栈操作函数的实现如`stack_creat`、`stack_empty`、`stack_push`、`stack_pop`等,以及在主函数`test.c`中的应用和`makefile`的编写。通过示例展示了链式栈的基本操作,如入栈、出栈、清空栈等。

被折叠的 条评论
为什么被折叠?



