栈的原理及实现
栈是一个先入后出(First In Last Out,)的线性表。元素的插入和删除只能在线性表的同一端进行。允许插入和删除的一端,为变化的一端,称为栈顶(Top),另一端为固定的一端,称为栈底(Bottom)。
运用的场合有:
浏览器网页的访问记录。
文本编辑器中的撤销功能。
充当其他数据结构和算法实现的一个组件。
栈的实现
两种很常见的实现方式:
-
数组实现
-
链表实现
#include"stack.h"
#include"..\fatal.h"
#include<stdlib.h>
#include<stdio.h>
#define EmptyTOS (-1)
#define MinStackSize (5)
typedef int ElementType;
struct StackRecord;
typedef struct StackRecord *Stack;
struct StackRecord{
int Capacity; //容量,即数组的最大长度
int TopOfStack; //栈顶
ElementType *Array; //实际存储元素的数组
};
int IsEmpty(Stack S){
return S->TopOfStack == EmptyTOS;
};
int IsFull(Stack S){
return S->TopOfStack == S->Capacity - 1;
}
Stack CreateStack(int MaxElements){
Stack S;
if(MaxElements < MinStackSize)
Error("Stack Size is too small.");
S = malloc(sizeof(struct StackRecord));
if(S == NULL)
FatalError("Out of Space!!");
S->Array = malloc(sizeof(ElementType) * MaxElements);
if(S->Array == NULL)
FatalError("Out of space!!");
S->Capacity = MaxElements;
MakeEmpty(S);
return S;
}
void MakeEmpty(Stack S){
S->TopOfStack = EmptyTOS;
}
void DisposeStack(Stack S){
if(S != NULL){
free(S->Array);
free(S);
}
}
void Push(Stack S, ElementType X){
if(IsFull(S))
Error("Full Stack");
else
S->Array[++S->TopOfStack] = X;
}
void Pop(Stack S){
if(IsEmpty(S))
Error("Empty Stack");
else
S->TopOfStack--;
}
ElementType Top(Stack S){
if(IsEmpty(S))
Error("Empty Stack");
else
return S->Array[S->TopOfStack];
}
ElementType TopAndPop( Stack S )
{
if( !IsEmpty( S ) )
return S->Array[ S->TopOfStack-- ];
Error( "Empty stack" );
return 0; /* Return value used to avoid warning */
}
下次补上栈的链表实现。
该文章会更新,欢迎大家批评指正。
推荐一个零声学院免费公开课程,个人觉得老师讲得不错,
分享给大家:[Linux,Nginx,ZeroMQ,MySQL,Redis,
fastdfs,MongoDB,ZK,流媒体,CDN,P2P,K8S,Docker,
TCP/IP,协程,DPDK等技术内容,点击立即学习:
服务器课程:C++服务器