源文件
#include "seq_stack.h"
//创建顺序栈
seq_p create_stack()
{
seq_p S = (seq_p)malloc(sizeof(seq_stack));
if (S == NULL)
{
printf("申请空间失败\n");
return NULL;
}
S->top = -1; //记录栈中没有元素
return S;
}
//判空
int empty_stack(seq_p S)
{
if (S == NULL)
{
printf("入参为空\n");
return -1;
}
return S->top == -1 ? 1 : 0;
}
//判满
int full_stack(seq_p S)
{
if (S == NULL)
{
printf("入参为空\n");
return -1;
}
return S->top == MAX - 1 ? 1 : 0;
}
//入栈(只能在栈顶操作)
void push_stack(seq_p S, datatype data)
{
if (S == NULL)
{
printf("入参为空,请检查\n");
return;
}
if (full_stack(S))
{
printf("栈已满\n");
return;
}
S->top++;
S->data[S->top] = data;
}
//输出栈中元素
void show_stack(seq_p S)
{
if (S == NULL)
{
printf("入参为空\n");
return;
}
if (empty_stack(S))
{
printf("栈为空\n");
return;
}
//要保留栈只能从栈顶操作的性质
for (int i = S->top; i >= 0; i--)
{
printf("%d\n", S->data[i]);
}
}
//出栈/弹栈
void pop_stack(seq_p S)
{
if (S == NULL)
{
printf("入参为空\n");
return;
}
if (empty_stack(S))
{
printf("栈空无需出栈\n");
return;
}
printf("%d\t",S->data[S->top--]);
}
void clean_stack(seq_p S)
{
if (S == NULL)
{
printf("入参为空\n");
return;
}
S->top = -1;
}
void free_stack(seq_p* S)
{
if (S == NULL || *S == NULL)
{
printf("入参为空\n");
return;
}
//释放堆区空间
free(*S);
*S = NULL;
}
头文件
#ifndef SEQ_STACK_H_
#define SEQ_STACK_H_
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
typedef int datatype;
typedef struct seq_stack
{
datatype data[MAX];
int top;
}seq_stack,*seq_p;
//创建顺序栈
seq_p create_stack();
void free_stack(seq_p* S);
#endif // !SEQ_STACK_H_