堆栈 :具有一定操作约束的线性表,只在一端做插入,删除,它的特点是后入先出,
就相当于羽毛球筒;
栈的顺序存储实现
#define MaxSize // 储存数据元素的最大个数
typedef struct SNode *Stack;
struct SNode{
ElementType Data[MaxSize];
int Top;
};
void Push(Stack PtrS,ElementType item){ //入栈
if(PtrS->Top=MaxSize-1){
printf("堆栈满");
return;
}
else {
PtrS->Data[++(PtrS->Top)]=item;
return;
}
}
ElementType Pop(Stack PtrS){
if(PtrS->Top==-1){
printf("堆栈空");
return ERROR;
}
else {
return (PtrS->Data[(PtrS->Top)--]);
}
}
堆栈的链式存储实现
栈的链式存储结构实际上就是一个单链表,叫做栈链。插入和删除都在栈顶进行;
typedef struct SNode *Stack;
struct SNode{
ElementType Data;
struct SNode *Next;
};
Stacck CreateStack(){//构建一个堆栈的头结点,返回指针
Stack S;
s=(Stack)malloc(sizeof(struct SNode));
s->Next=NULL;
return S;
}
int IsEmpty(Stack S){ //判断堆栈是否为空
return (S->Next=NULL);
}
void Push(ElementType item,Stack S){ //将元素item压入堆栈S
struct SNode *TmpCell;
TmpCell=(struct SNode *)malloc(sizeof (struct SNode));
TmpCell->Element=item;
TmpCell->Next=S->Nect;
s->Next=TmpCell;
}
ElementType Pop(Stack S){ //删除并返回堆栈s的栈顶元素
struct SNode *FirstCell;
ElementType TopElem;
if(IsEmpty(s)){
printf("堆栈空");
return NULL;
}
else {
FirstCell=S->Next;
S->Next=FirstCell->Next;
TopElem=FirstCell->Element;
free(FirstCell);
return TopElem;
}
}
堆栈的入队和出队操作在队头进行