堆栈基础
堆栈(Stack) :具有一定操作约束的线性表,只在一端(栈顶,Top)做插入、删除。
插入数据:入栈(Push)
删除数据:出栈(Pop)
后入先出:Last In First Out(LIFO)
数据对象集:一个有0个或多个元素的又穷线性表。
操作集:长度为MaxSize的堆栈S∈Stack,堆栈元素item∈ElementType
Pop和Push可以穿插进行
栈的顺序存储实现
#define MaxSize<储存数据元素的最大个数>
typedef struct SNode *Stack;
struct SNode{
ElementType Data[MaxSize];
int Top;
};
入栈(Push)
void Push(Stack PtrS, ElementType item)
{
if (Ptrs->Top==MaxSize-1){
printf("堆栈满");return;
}else {
Ptrs->Data[++(PtrS->Top)]=item;
return ;
}
}
出栈(Pop)
ElementType Pop(Stack PtrS)
{
if(PtrS->Top==-1){
printf("堆栈空");
return ERROR;
}else
return(PtrS->Data[(PtrS->Top)--]);
}
一个数组两个堆栈
#define MaxSize<储存数据元素的最大个数>
typedef struct SNode *Stack;
struct SNode{
ElementType Data[MaxSize];
int Top1;/*堆栈1的栈顶指针*/
int Top2;/*堆栈2的栈顶指针*/
}S;
S.Top=-1;/*堆栈空*/
S.top2=MaxSize;/*堆栈空*/
一数组双栈法:入栈(Push)
void Push( struct DStack *PtrS, ElementType item, int Tag )
{ /* Tag作为区分两个堆栈的标志,取值为1和2 */
if ( PtrS->Top2 - PtrS->Top1 == 1) { /*堆栈满*/
printf ("堆栈满") ; return ;
}
if ( Tag == 1 )/*对第一个堆栈操作*/
PtrS->Data [++ (PtrS-> Top1) ] = item;
else /* 对第二 个堆栈操作*/
PtrS->Data[-- (PtrS->Top2) ] = item;
}
一数组双栈法:出栈(Pop)
ElementType Pop( struct DStack *PtrS,int Tag )
{ /* Tag作为区分两个堆栈的标志,取值为1和2 */
if(Tag==1){/*对第一个堆栈操作*/
if ( Ptrs->Top1 == -1 ) { /*堆栈1空 */
printf ("堆栈1空") ; return NULL;
} else return PtrS->Data[ (PtrS->Top1)--] ;
} else { /*对第二个堆栈操作*/
if ( Ptrs->Top2 == MaxSize ) { /*堆栈2空*/
printf ("堆栈2空") ; return NULL;
} else return PtrS->Data[ (PtrS->Top2) ++] ;
}
}
堆栈的链式存储实现
- 堆栈初始化(建立空栈)
- 判断堆栈S是否为空
typedef struct SNode *Stack;
struct SNode{
ElementType Data;
struct SNode *Next;
};
Stack CreateStack ()
{ /*构建一个堆栈的头结点,返回指针*/
Stack S; .
S =(Stack) malloc (sizeof (struct SNode)) ; .
S->Next = NULL;
return S;
}
int IsEmpty (Stack S)
{ /*判断堆栈s是否为空,若为空函数返回整数1,否
则返回0 */
return ( S->Next == NULL ) ;
}
链式入栈(Push)
void Push( ElementType item, Stack S)
{ /*将元素item压入堆栈s */
struct SNode *TmpCell;
TmpCell= (struct SNode *)malloc (sizeof (struct SNode)) ;
TmpCell->Element = i tem ;
TmpCel1->Next = S->Next ; .
S->Next = TmpCell;
}
链式出栈(Pop)
ElementType Pop (Stack S)
{ /*删除并返回堆栈s的栈项元素*/
struct SNode *FirstCel1 ;
ElementType TopElem ;
if( IsEmpty( S ) ) {
printf ("堆栈空"); return NULL;
} else {
FirstCell = S->Next;
S->Next = FirstCell->Next ;
TopElem = FirstCel1 ->Element ;
free (FirstCe11) ;
return TopElem ;
}
}
笔记来源mooc,陈越老师、何钦铭老师课程数据结构