前言
本文是关于堆栈的基本操作学习,包括顺序存储和链式存储两种形式。
一、顺序存储的定义和操作
顺序存储的优点:在实现和操作上都比链栈容易
顺序存储的缺点:存储空间只能事先申请,所以当数据量较大时要注意栈溢出的问题。
1.定义与创建
typedef int Position;
struct SNode{
ElementType *Data; //存储元素的数组
Position Top; //栈顶指针
int MaxSize; //堆栈最大容量
};
typedef struct SNode *Stack;
Stack CreateStack(int MazSize){
Stack S =(Stack)malloc(sizeof(struct SNode));
S->Data = (ElementType *)malloc(MaxSize *sizeof(ElementType));
S->Top = -1;
S->MaxSize = MaxSize;
return S;
}
2.判满
/*判满*/
bool IsFull(Stack S){
return (S->Top == S->MaxSize-1);
}
3.入栈
/*入栈*/
bool Push(Stack S,ElementType x){
if(IsFull(S)){
cout<<"堆栈满"<<endl;
return false;
}
else{
S->Data[++(S->Top)] = x;
return true;
}
}
4.判空
/*判空*/
bool IsEmpty(Stack S){
return (S->Top == -1);
}
5.出栈
/*出栈*/
ElementType Pop(Stack S){
if(IsEmpty(S)){
cout<<"堆栈空"<<endl;
return ERROR;//Element标记错误的特殊值
}
else
return (S->Data[(S->Top)--]);
}
二、链式存储的定义和操作
链式存储的优点:可以存储的数据数量更为灵活,不用担心栈溢出的问题
链式存储的缺点:实现过程较为复杂。
1.定义与创建
typedef struct SNode *PtrSNode;
struct SNode{
ElementType Data;
PtrSNode Next;
};
typedef PtrSNode Stack;
Stack CreateStack(){
/*创建一个堆栈的头结点*/
Stack S;
S = (Stack)malloc(sizeof(struct SNode));
S->Next = NULL;
return S;
}
2.判空
/*判空*/
bool IsEmpty(Stack S){
return(S->Next == NULL);
}
3.入栈
/*入栈*/
bool Push(Stack S,ElementType x){
PtrSNode TmpCell;
TmpCell = (PtrSNode)malloc(sizeof(struct SNode));
TmpCell->Data = x;
TmpCell->Next = S->Next;
S->Next = TmpCell;
return true;
}
4.出栈
/*出栈*/
ElementType Pop(Stack S){
PtrSNode FirstCell;
ElementType TopElem;
if(IsEmpty(S)){
cout<<"堆栈空"<<endl;
return ERROR;//ElementType的错误参数
}
else{
FirstCell = S->Next;
TopElem = FirstCell->Data;
S->Next = FirstCell->Next;
free(FirstCell);
return TopElem;
}
}
三、双栈共享空间
1.定义
typedef int Position;
struct SNode{
ElementType *Data;
int MaxSize;
Position Top1;
Position Top2;
};
typedef struct SNode *Stack;
2.入栈
/*入栈*/
bool Push(Stack S,ElementType x,int StackNum){
if(S->Top1==S->Top2-1){
cout<<"堆栈满"<<endl;
return false;
}
if(StackNum == 1)
S->Data[++S->Top1] = x;
else if(StackNum == 2)
S->Data[--S->Top2] = x;
return true;
}
3.出栈
/*出栈*/
ElementType Pop(Stack S,int StackNum){
if(StackNum == 1){
if(S->Top1 == -1){
cout<<"堆栈空"<<endl;
return ERROR;
}
else
return(S->Data[S->Top1--]);
}
else if(StackNum == 2){
if(S->Top2 == S->MaxSize){
cout<<"堆栈空"<<endl;
return ERROR;
}
else
return(S->Data[S->Top2++]);
}
}