代码分为4部分的test.c. head.h list.c Makefile
list.c
#include"head.h"
//创建一个空栈
sqstack stack_create(int len)
{
sqstack p;
p=(sqstack)malloc(sizeof(Lnode));
if(p==NULL)
{
printf("p apply is failed\n");
return NULL;
}
p->date=(int *)malloc(len*sizeof(int));
if(p->date==NULL)
{
printf("p->date apply is failded\n");
return NULL;
}
p->maxlength=len;
p->top=-1;
return p;
}
//判断栈是否为满
int stack_full(sqstack s)
{
return s->top==s->maxlength-1?1:0;
}
//清空栈区
void stack_clear(sqstack s)
{
s->top=-1;
printf("s->top is empty\n");
}
//判断栈区是否为空
int stack_empty(sqstack s)
{
return s->top==-1?1:0;
}
//入栈
int stack_push(sqstack s,int value)
{
if(s->top==s->maxlength-1)
{
printf("stack is full\n");
return 1;
}
s->date[s->top+1]=value;
s->top++;
return 0;
}
//出栈
int stack_pop(sqstack s)
{
int value;
s->top--;
value=s->date[s->top+1];
return value;
}
//访问的栈顶的元素
int stack_top(sqstack s)
{
return s->date[s->top];
}
int stack_free(sqstack s)
{
free(s->date);
s->date=NULL;
free(s);
s=NULL;
return 0;
}
test.c
#include"head.h"
int main(int argc,char *argv[])
{
sqstack s;
int n=4;
s=stack_create(n);
//printf("%d ",s->maxlength);
stack_push(s,10);
stack_push(s,20);
stack_push(s,30);
stack_push(s,40);
stack_push(s,50);
while(!stack_empty(s))
{
printf("%d ",stack_pop(s));
}
printf("\n");
stack_clear(s);
stack_free(s);
// stack_free(s);
return 0;
}
head.h
#ifndef __HEAD_H
#define __HEAD_H
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct stack_list{
int *date;//结构没有内存,需要自己去申请
int maxlength;
int top;
}Lnode,*sqstack;
sqstack stack_create(int len);
int stack_empty(sqstack s);
void stack_clear(sqstack s);
int stack_full(sqstack s);
int stack_push(sqstack s,int value);
int stack_pop(sqstack s);
int stack_top(sqstack s);
int stack_free(sqstack s);
#endif
Makefile
CC=gcc
CFLAGS=-c -O -Wall
obj=list.o test.o
yuxiang:$(obj)
$(CC) -o $@ $^
%*.o:%*.c
$(CC) $(CFLAGS) -o $@ $<
.PHONY:clean
clean:
rm -rf *.o yuxiang