可以用数组来表示栈的结构。定义一个结构体,其中有一个数组,动态分配内存。top记录栈顶。
头文件
#ifndef _HEAD_H
#define _HEAD_H
#define MINSIZE 5 //定义最小长度为5
#define EMPTY -1 //栈空情况
typedef int ElementType;
typedef struct node* Stack;
typedef struct node{
ElementType* array;
int arrayMaxLength; //记录动态分配的数组长度
int top; //记录栈顶(数组下标表示)
}Node;
Stack CreateStack(void);
void Push(Stack ss, ElementType x);
void Pop(Stack ss);
void FreeSpace(Stack ss);
void Display(Stack ss);
void MakeEmpty(Stack ss);
int IsEmpty(Stack ss);
int IsFull(Stack ss);
void clean(void);
#endif
操作集
#include<stdio.h>
#include<stdlib.h>
#include "head.h"
Stack CreateStack(void)
{
Stack S;
printf("输入数组长度(大于%d):", MINSIZE);
int length;
while(scanf("%d", &length))
{
if (length >= MINSIZE)
break;
else
printf("输入数组长度(大于%d):", MINSIZE);
}
S = (Stack)malloc(sizeof(Node));
if (S == NULL)
{
printf("out of space!");
exit(EXIT_FAILURE);
}
S->array = (ElementType*)malloc(length*sizeof(ElementType));
if (S->array == NULL)
{
printf("out of space!");
exit(EXIT_FAILURE);
}
S->arrayMaxLength = length;
MakeEmpty(S);
return S;
}
void Push(Stack ss, ElementType x)
{
if (IsFull(ss))
{
printf("the stack is full.\n");
return;
}
ss->array[++ss->top] = x;
}
void Pop(Stack ss)
{
if (IsEmpty(ss))
{
printf("the stack is Empty.\n");
return;
}
ss->top--;
}
void clean(void)
{
while(getchar() != '\n')
continue;
}
int IsEmpty(Stack ss)
{
return ss->top == EMPTY;
}
int IsFull(Stack ss)
{
return ss->top == ss->arrayMaxLength - 1;
}
void MakeEmpty(Stack ss)
{
ss->top = EMPTY;
}
void Display(Stack ss)
{
if (ss == NULL)
{
printf("the stack point is null\n");
exit(EXIT_FAILURE);
}
if (IsEmpty(ss))
{
printf("The stack is empty\n");
return ;
}
int length = ss->top + 1;
printf("%d data:", length);
for (int i = 0; i < length; i++)
{
printf("|%d|",ss->array[i]);
if (i != length - 1)
{
printf("->");
}
}
printf("\n");
}
void FreeSpace(Stack ss)
{
if (ss != NULL)
{
free(ss->array);
free(ss);
}
}
主函数
#include<stdio.h>
#include "head.h"
int main(void)
{
printf("创建一个栈\n");
Stack S = CreateStack();
Display(S);
printf("*******************************************\n");
printf("压栈操作\n");
printf("请输入你要入栈的元素,输入字母结束\n");
ElementType element;
while(scanf("%d", &element))
{
Push(S, element);
}
Display(S);
printf("*******************************************\n");
printf("弹栈操作\n");
Pop(S);
Display(S);
printf("*******************************************\n");
printf("清空栈操作\n");
MakeEmpty(S);
Display(S);
printf("*******************************************\n");
printf("释放内存操作\n");
FreeSpace(S);
S->array = NULL;//释放内存只是将指针指向的内存中的数据清了,指针并没有指向NULL,在这里置NULL,不要让指针是一个野指针。
S = NULL;
Display(S);
return 0;
}
下标大的元素是接近栈顶的。