问题描述:顺序栈的实现(功能实现:创建栈,进栈,出栈,释放内存等操作)。
代码实现:
实现一个功能函数需要三个文件(三个文件在同一目录)。
sqstack.h(定义顺序表)
sqstack.c(实现接口函数)
test.c(主函数实现)
sqstack.h
定义各种函数。包括创建栈sqstack * stack_create(int len);
入栈int stack_push(sqstack * s, data_t value);
**出栈data_t stack_pop(sqstack s);
释放内存int stack_free(sqstack s);
typedef int data_t;
typedef struct {
data_t *data;
int maxlen;
int top;
}sqstack;
sqstack * stack_create(int len);
int stack_push(sqstack * s, data_t value);
int stack_empty(sqstack *s);
int stack_full(sqstack *s);
data_t stack_pop(sqstack *s);
data_t stack_top(sqstack *s);
int stack_clear(sqstack *s);
int stack_free(sqstack *s);
sqstack.c
上述定义的函数实现。
#include "sqstack.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
sqstack * stack_create(int len) {
sqstack * s;
if ((s =(sqstack *)malloc(sizeof(sqstack))) == NULL) {
printf("malloc sqstack failed\n");
return NULL;
}
if ((s->data = (data_t *)malloc(len * sizeof(data_t)))==NULL) {
printf("malloc data failed\n");
free(s);
return NULL;
}
memset(s->data, 0, len*sizeof(data_t));
s->maxlen = len;
s->top = -1;
return s;
}
/*
* @ret 1-empty
*/
int stack_empty(sqstack *s){
if (s == NULL){
printf("s is NULL\n");
}
return (s->top == -1 ? 1 : 0);
}
/*
* @ret 1-full
*/
int stack_full(sqstack *s) {
if (s == NULL){
printf("s is NULL\n");
}
return (s->top == s->maxlen-1 ? 1 : 0);
}
int stack_push(sqstack * s, data_t value) {
if (s == NULL) {
printf("s is NULL\n");
return -1;
}
if (s->top == s->maxlen-1) {
printf("stack is full\n");
return -1;
}
s->top++;
s->data[s->top] = value;
return 0;
}
data_t stack_pop(sqstack *s) {
s->top--;
return (s->data[s->top+1]);
}
data_t stack_top(sqstack *s){
return (s->data[s->top]);
}
int stack_clear(sqstack *s) {
if (s == NULL) {
printf("s is NULL\n");
return -1;
}
s->top = -1;
return 0;
}
int stack_free(sqstack *s) {
if (s == NULL) {
printf("s is NULL\n");
return -1;
}
if (s->data != NULL)
free(s->data);
free(s);
return 0;
}
test.c
主函数程序:首先创建了一个大小为100的栈,依次入栈4个整数值,分别是10,20,30,40。调用出栈函数,打印元素。最后调用stack_free释放栈所占内存。
#include <stdio.h>
#include "sqstack.h"
int main(int argc, const char *argv[])
{
sqstack *s;
s = stack_create(100);
if (s == NULL)
return -1;
stack_push(s, 10);
stack_push(s, 20);
stack_push(s, 30);
stack_push(s, 40);
while (!stack_empty(s)) {
printf("pop: %d \n", stack_pop(s) );
}
stack_free(s);
return 0;
}
运行结果:
由上述结果图可知,成功运行创建栈,入栈4个整数,出栈及释放内存等操作。(后进先出)