資料結構中順序棧c語言程式碼實現
一.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;
}
三.makefile實現
CFLAGS=-c -Wall -g
test:sqstack.o test.o
.PHONY:clean
clean:
rm *.o test
四.測試函式的實現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;
}