数据结构之栈
本文讨论栈的数组实现。
栈需要有如下几个属性:
- 栈的容量(Capacity)
- 栈顶指针
- 存储栈元素的数组
根据这几个属性可以定义一个栈结构体:
struct StackRecord
{
int Capacity;
int TopOfStack;
DataType *Array;
};
然后定义栈的操作,一般可以包含如下几个:
- 栈的创建:Stack CreateStack(int size);
- 栈的销毁:void DisposeStack(Stack S);
- 判断栈空:int IsEmpty(Stack S);
- 判断栈满:int IsFull(Stack S);
- 进栈:void Push(DataType data, Stack S);
- 出栈:void Pop(Stack S);
- 查看栈顶元素:DataType Top(Stack S);
- 查看栈顶元素并弹出:DataType TopAndPop(Stack S);
下面是完整的实现代码:
Stack.h
:
#ifndef STACK_H
#define STACK_H
#define MinStackSize 5
struct StackRecord;
typedef int DataType;
typedef struct StackRecord *Stack;
int IsEmpty(Stack S);
int IsFull(Stack S);
Stack CreateStack(int size);
void DisposeStack(Stack S);
void Push(DataType data, Stack S);
DataType Top(Stack S);
void Pop(Stack S);
DataType TopAndPop(Stack S);
#endif
Stack.c
:
#include <stdlib.h>
#include "Stack.h"
struct StackRecord
{
int Capacity;
int TopOfStack;
DataType *Array;
};
Stack CreateStack(int size)
{
Stack S;
if (size < MinStackSize)
{
exit(0);
}
S = malloc(sizeof(struct StackRecord));
if (S == NULL)
{
exit(0);
}
S->Array = malloc(sizeof(DataType) * size);
if (S->Array == NULL)
{
exit(0);
}
S->Capacity = size;
S->TopOfStack = -1;
return S;
}
void DisposeStack(Stack S)
{
if (S != NULL)
{
free(S->Array);
free(S);
}
}
int IsEmpty(Stack S)
{
return S->TopOfStack == -1;
}
int IsFull(Stack S)
{
return S->TopOfStack == S->Capacity - 1;
}
void Push(DataType data, Stack S)
{
if (IsFull(S))
{
exit(0);
}
else
{
S->Array[++S->TopOfStack] = data;
}
}
void Pop(Stack S)
{
if (IsEmpty(S))
{
exit(0);
}
else
{
S->TopOfStack--;
}
}
DataType Top(Stack S)
{
if (!IsEmpty(S))
{
return S->Array[S->TopOfStack];
}
exit(0);
}
DataType TopAndPop(Stack S)
{
if (!IsEmpty(S))
{
return S->Array[S->TopOfStack--];
}
exit(0);
}
UseStack.c
:
#include <stdio.h>
#include "Stack.h"
void main()
{
Stack S = CreateStack(20);
printf("---------------------\n");
for(int i=0;i<20;i++)
{
Push(i+1,S);
}
for (int i = 0; i < 20; ++i)
{
printf("|%d",TopAndPop(S));
printf("|");
}
}
参考:数据结构与算法分析:C语言描述(第二版)