类型名称:堆栈(Stack)
数据对象集:一个有0个或者多个元素的有穷线性表
操作集:一个具体长度MaxSize的堆栈S∈Stack,记堆栈中的任一元素X∈ElementType
(1):Stack CreateStack(int MaxSize):生成空堆栈,最大长度MaxSize
(2):bool IsFull(Stack S)判断堆栈是否满
(3):bool Push(Stack S,ElementType X)将X压入堆栈
(4):ElementType Pop(Stack S)删除并返回栈顶元素
栈的顺序存储实现
typedef int Position;
typedef struct SNode * PtrToSNode;
struct SNode{
ELementType * Data;
Position Top;
int MaxSize;
};
typedef PtrToSNode Stack;
顺序栈的创建
Stack CreateStack(int MaxSize)
{
Stack S=(Stack)malloc(sizeof(struct SNode));
S->Data=(ElementType * )malloc(MaxSize * sizeof(ElementType));
S->Top=-1;
S->MaxSize=MaxSize;
return S;
}
入栈
bool IsFull(Stack S)
{
return (S->Top==S->MaxSize-1);
}
bool Push(Stack S,ElementType X)
{
if(IsFull(S))
{
return false;
}
else
{
S->Data[++(S->Top)]=X;
return true;
}
}
出栈
bool IsEmpty(Stack S)
{
return (S->Top==-1);
}
ElementType Pop(Stack S)
{
if(IsEmpty(S))
return false;
}
else
{
return (S->Data[(S->Top)--]);
}
堆栈的链式存储实现
定义
typedef struct SNode * PtrToSNode;
struct SNode{
ElementType Data;
PtrToSNode Next;
};
typedef PtrToSNode Stack;
链式栈的创建
Stack CreateStack()
{
Stack S:
S=malloc(sizeof(struct SNode));
S->Next=NULL;
return S;
}
判断栈空
bool IsEmpty(Stack S)
{
return (S->Next==NULL);
}
压栈
bool Push(Stack S,ElementType S)
{
PtrToSNode TmpCell;
TmpCell=(PtrToSNode)malloc(sizeof(struct SNode));
TmpCell->Data=X;
TmpCell->Next=S->NextS->Next=TmpCell;
}
return true;
}
删除
ElementType Pop(Stack S)
{
PtrToSNode FirstCell;
ElementType TopElem;
if(IsEmpty(S))
{
return ERROR;
}
else
{
FIrstCell=S->Next;
TopElem=FirstCell->Data;
S->Next=FirstCell->Next;
free(FirstCell);
return TopElem;
}
}