堆栈的抽象数据类型定义为:
类型名称:堆栈(Stack)
数据对象集:一个有0个或多个元素的有穷线性表
操作集:堆栈的基本操作主要有
typedef int Position;
typedef struct SNode *PtrToSNode;
struct SNode
{
ElementType *Data; /*数组*/
Position Top; /*栈顶指针*/
int MaxSize;
};
typedef PtrToSNode Stack;
1.生成空堆栈(给定容量)
Stack CreateStack(int MaxSize)
{
Stack S=(Stack)malloc(sizeof(struct SNode));
S->Data=(Element *)malloc(MaxSize*sizeof(struct SNode));
S->Top=-1;
S->MaxSize=MaxSize;
return S;
}
2.判断堆栈S是否已满
bool IsFull(Stack S)
{
return(S->Top==S->MaxSize-1);
}
3.入栈(将元素X压入堆栈)
bool Push(Stack S,ElementType X)
{
if(IsFull(S))
{
printf("堆栈满");
return false;
}
else
{
S->Data[++(S->Top)]=X;
return true;
}
}
4.判断堆栈S是否为空
bool IsEmpty(Stack S)
{
return(S->Top==-1);
}
5.出栈(删除并返回栈顶元素)
ElementType Pop(Stack S)
{
if(IsEmpty(S))
{
printf("堆栈空");
return ERROR; /*ERROR是ElementType的特殊值,标志错误*/
}
else
{
return(S->Data[(S->Top)--]);
}
}
双堆栈结构
1.创建
typedef int Position;
typedef struct SNode *PtrToSNode;
struct SNode
{
ElementType *Data;
Position Top1;
Position Top2;
int MaxSize;
};
typedef PtrToSNode Stack;
2.入栈
bool Push(Stack S,ElementType X,int Tag)
{
/*Tag作为区分两个堆栈的标志,取值为1和2*/
if(S->Top2-S->Top1==1)
{
printf("堆栈满\n"); /*堆栈满不用判断两次,因为两个堆栈在数组*/
return false;
}
else
{
if(Tag==1) S->Data[++(S->Top1)]=X;
else S->Data[--(S->Top2)]=X;
return true;
}
}
3.出栈
ElementType Pop(Stack S,int Tag)
{
if(Tag==1)
{
if(S->Top1==-1)
{
printf("堆栈1空\n");
return ERROR;
}
else return S->Data[(S->Top1)--];
}
else
{
if(S->Top2==S->MaxSize)
{
printf("堆栈2空\n");
return ERROR;
}
else return S->Data[(S->Top2)++];
}
}
堆栈的链式存储实现
typedef struct SNode *PtrToSNode;
struct SNode
{
ElementType Data;
PtrToSNode Next;
};
typedef PtrToSNode Stack;
1.创建
Stack CreateStack()
{
/*构建一个堆栈的头结点,返回该结点指针*/
Stack S;
S=malloc(sizeof(struct SNode)); /*不需要将存储空间强制转化为Stack么?*/
S->Next=NULL;
return S;
}
2.入栈
bool IsEmpty(Stack S)
{
return(S->Next==NULL);
}
bool Push(Stack S,EmementType X)
{
PtrToSNode TmpCell;
TmpCell=(PtrToSNode)malloc(sizeof(struct SNode));
TmpCell->Data=X;
TmpCell->Next=S->Next;
S->Next=TmpCell;
return true;
}
/*堆栈以链式存储结构(链栈)存储时,不需要判断堆栈是否已满*/
3.出栈
ElementType Pop(Stack S)
{
PtrToSNode FirstCell;
ElementType TopElem;
if(IsEmpty(S))
{
printf("堆栈空");
return ERROR;
}
else
{
FirstCell=S->Next; /*S是最后一个元素的前一个元素么?*/
TopElem=FirstCell->Data;
S->Next=FirstCell->Next;
free(FirstCell);
return TopElem;
}
}