栈的数组实现
1、头文件
(Stack2.h)
#pragma once
/*
* 栈的数组实现
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define EmptyTos (-1)
#define MinStackSize (5)
struct Stack* createStack(int MaxElements);
bool isEmpty(struct Stack* s);
bool isFull(struct Stack* s); //判断栈是否满
void disposeStack(struct Stack* s); //释放栈的内存
void makeEmpty(struct Stack* s);
void push(int x, struct Stack* s);
int top(struct Stack* s);
void pop(struct Stack* s);
int topAndPop(struct Stack* s);
void printStack(struct Stack* s); //打印栈
struct Stack
{
int topOfStack; //栈顶角标,用于控制栈的有效数据范围
int capacity; //栈的容量
int* array; //指针,指向一维数组首元素的地址
};
2、主函数
(main.c)
#include "Stack2.h"
int main()
{
int val;
struct Stack* s;
//创建一个栈
s = createStack(10);
//压栈
push(5, s);
push(2, s);
//显示栈中的元素值
printStack(s);
printf("\n-------------------------\n");
//查看栈顶元素值
val = top(s);
printf("top val is:%d\n", val);
printf("-------------------------\n");
//栈顶元素出栈
pop(s);
val = top(s);
printf("top val is:%d\n", val);
printf("-------------------------\n");
push(6, s);
push(7, s);
printStack(s);
printf("\n-------------------------\n");
//清空栈
makeEmpty(s);
printf("Stack isEmpty:%d\n", isEmpty(s));
//如果栈不再使用,则释放栈内存
disposeStack(s);
return 0;
}
3、函数实现
3.1 createStack.c
#include "Stack2.h"
struct Stack* createStack(int maxElements)
{
struct Stack* s;
if (maxElements < MinStackSize) {
printf("栈的的容量过小");
return NULL;
}
s = malloc(sizeof(struct Stack));
if (NULL == s) {
printf("内存空间不足,创建栈是失败");
exit(1);
}
s->array = malloc(sizeof(int) * maxElements);
if (NULL == s->array) {
printf("内存空间不足,创建栈失败");
exit(1);
}
s->capacity = maxElements;
s->topOfStack = EmptyTos;
return s;
}
3.2 isEmpty.c
#include "Stack2.h"
bool isEmpty(struct Stack* s)
{
return EmptyTos == s->topOfStack;
}
3.3 isFull.c
#include "Stack2.h"
bool isFull(struct Stack* s)
{
return s->capacity == s->topOfStack + 1;
}
3.4 disposeStack.c
#include "Stack2.h"
void disposeStack(struct Stack* s)
{
if (s != NULL) {
free(s->array);
free(s);
s->array = NULL;
s = NULL;
}
}
3.5 makeEmpty
#include "Stack2.h"
void makeEmpty(struct Stack* s)
{
s->topOfStack = EmptyTos;
}
3.6 push.c
#include "Stack2.h"
void push(int x, struct Stack* s)
{
if (s->capacity <= s->topOfStack + 1) {
printf("栈的最大空间不足以再容纳数据了。");
return;
}
s->array[++s->topOfStack] = x;
}
3.7 top.c
#include "Stack2.h"
int top(struct Stack* s)
{
if (isEmpty(s)) {
printf("此栈为空,无法打印栈顶");
return 0;
}
return s->array[s->topOfStack];
}
3.8 pop.c
#include "Stack2.h"
void pop(struct Stack* s)
{
if (isEmpty(s)) {
printf("此栈为空,无法pop\n");
return;
}
s->topOfStack--;
}
3.9 topAndPop.c
#include "Stack2.h"
int topAndPop(struct Stack* s)
{
if (!isEmpty(s)) {
return s->array[s->topOfStack--];
}
printf("empty stack\n");
return 0;
}
3.10 printStack.c
#include "Stack2.h"
void printStack(struct Stack* s)
{
if (s->topOfStack == -1) {
printf("此栈为空,无法打印");
return;
}
for (int i = 0; i <= s->topOfStack; i++) {
printf("%d ", s->array[i]);
}
}
4、写在后面
为方便大家学习,我已经将原码上传到了GitHub,欢迎大家下载。链接:link(文件名为:栈的数组实现)