#pragma once
#include <stdio.h>
#include <stdlib.h>
typedef int data_t;
typedef struct
{
data_t* data;//数据类型
int max_lenth;//栈的最大容量
int top;//栈顶位置下标
}sqstack, *pstack;
//创建顺序栈,返回结构体sqstack的地址
pstack stack_creat(int lenth);
//入栈操作
int stack_push(pstack p, data_t* val);
//出栈操作,返回出栈元素的值
data_t stack_pop(pstack p);
//打印栈
void stack_show(pstack p);
//清空栈
int stack_clear(pstack p);
//释放动态开辟的空间
int stack_free(pstack p);
头文件stack.h
#include "stack.h"
pstack stack_creat(int lenth)
{
pstack s;
s = (pstack)malloc(sizeof(sqstack));
s->data = (data_t*)malloc(sizeof(data_t) * lenth);
s->max_lenth = lenth;
s->top = -1;//栈顶下标为-1时为空栈
return s;
}
int stack_push(pstack p, data_t* val)
{
if (p == NULL)
{
//printf("Pointer is NULL.\n");
return -1;
}
if (p->top == p->max_lenth - 1)
{
//printf("Stack is full.\n");
return -1;
}
(p->top)++;
*(p->data + p->max_lenth - p->top - 1) = *val;
return 0;
}
data_t stack_pop(pstack p)
{
data_t temp;
if (p == NULL)
{
//printf("Pointer is NULL.\n");
return -1;
}
if (p->top == - 1)
{
//printf("Stack is empty.\n");
return -1;
}
temp = *(p->data + p->max_lenth - p->top - 1);
*(p->data + p->max_lenth - p->top - 1) = 0;
(p->top)--;
return temp;
}
void stack_show(pstack p)
{
if (p == NULL)
{
//printf("Pointer is NULL.\n");
return;
}
if (p->top == -1)
{
printf("Stack is empty.\n");
}
int temp = p->top;
while (p->top != -1)
{
printf("%d\t%p\n", *(p->data + p->max_lenth - p->top - 1),
p->data + p->max_lenth - p->top - 1);
(p->top)--;
}
p->top = temp;
}
int stack_clear(pstack p)
{
if (p == NULL)
{
//printf("Pointer is NULL.\n");
return -1;
}
if (p->top == -1)
{
//printf("Stack is empty.\n");
return -1;
}
while (p->top != -1)
{
*(p->data + p->max_lenth - p->top - 1) = 0;
(p->top)--;
}
return 0;
}
int stack_free(pstack p)
{
if (p == NULL)
{
//printf("Pointer is NULL.\n");
return -1;
}
free(p->data);
free(p);
return 0;
}
函数实现stack.c
#include "stack.h"
int main()
{
pstack p;
p = stack_creat(10);
//test
for (int i = 0; i < 5; i++)
{
stack_push(p, &i);
}
stack_show(p);
printf("##############\n");
stack_pop(p);
stack_show(p);
printf("##############\n");
stack_clear(p);
stack_show(p);
printf("##############\n");
stack_free(p);
//
return 0;
}
测试部分test.c
运行结果
需要注意的是,栈是由高地址向低地址生长的,也就是说栈底是高地址,栈顶是低地址,出栈入栈操作都只能对栈顶进行。