栈又称堆栈,它是一种运算受限的线性表,其限制是仅允许在表的一端进行插入和删除运算。一般把对栈进行运算的一端称为栈顶,另一端称为栈底。
一,栈的顺序存储:
struct StackSq{
ElemType* stack;
int top;
int MaxSize;
};
初始化栈S为空:
void InitStack(struct StackSq* S,int ms)
{
if(ms<=0){printf("ms is not valide!\n");exit(1);}
S->MaxSize=ms;
S->stack=malloc(ms*sizeof(ElemType));
if(!S->stack){
printf("malloc failed!\n");
exit(1);
}
S->top=-1;
}
新元素进栈,即把它插入到栈顶
void Push(struct StackSq* S,ElemType x)
{
if(S->top==S->MaxSize-1) againMalloc(S);
S->top++;
S->stack[S->top]=x;
}
void againMalloc(struct StackSq)
{
ElemType *p;
p=realloc(S->stack,2*S->MaxSize*sizeof(ElemType));
if(!p){
printf("realloc failed!\n");
exit(1);
}
S->stack=p;
S->MaxSize=2*S->MaxSize;
}
删除栈顶元素并返回值
ElemType Pop(struct StackSq* S)
{
if(S->top==-1){
printf("stack is empty!\n");
exit(1);
}
S->top--;
return S->stack[S->top+1];
}
读取栈顶元素的值
ElemType Peek(struct StackSq *S)
{
if(S->top==-1){
printf("stack is empty!\n");
exit(1);
}
return S->stack[S->top];
}
判断S是否为空,若是则返回1表示真,否则返回0表示假
int EmptyStack(struct StackSq* S)
{
if(S->top==1)return 1;else return 0;
}
清除栈S中的所有元素,释放动态存储空间
void ClearStack(struct StackSq* S)
{
if(S->stack){
free(S->stack);
S->stack=0;
S->top=1;
S->MaxSize=0;
}
}
二,
栈的链接存储:
栈的链接存储结构与线性表的链接存储结构相同,也是通过由结点构成的单链表实现的,此时表头指针被称为栈顶指针,由栈顶指针指向的表头结点被称为栈顶结点,整个单链表被称为链栈,即链接存储的栈。
初始化链栈为空
void InitStack(struct sNode** HS)
{
*HS=NULL;
}
向链栈中插入一个元素
void Push(struct sNode** HS,ElemType x)
{
struct sNode *newp;
newp=malloc(sizeof(struct sNode));
if(newp==NULL){
printf("malloc failed!\n");
exit(1);
}
newp->data=x;
newp->next=*HS;
*HS=newp;
}
从链栈中删除一个元素并返回它
ElemType Pop(struct sNode** HS)
{
struct sNode* p;
ElemType tmp;
if(*HS==NULL){
printf("Stack is empty!\n");
exit(1);
}
p=*HS;*HS=p->next;
tmp=p->data;
free(p);
return tmp;
}
读取栈顶元素
ElemType Peek(struct sNode** HS)
{
if(*HS==NULL){
printf("Stack is empty!\n");
exit(1);
}
return (*HS)->data;
}
检查链栈是否为空
int EemptyStack(struct sNode** HS)
{
if(*HS==NULL)return 1;else return 0;
}
清空链栈
void ClearStack(struct sNode** HS)
{
struct sNode *cp,*np;
cp=*HS;
while(cp!=NULL){
np=cp->next;
free(cp);
cp=np;
}
*HS=NULL;
}
栈的一个非常重要应用场景就是递归。