栈的顺序存储实现
#define MaxSize<存储数据元素的最大个数>
typedef struct SNode *Stack;
struct SNode{
ElementType Data[MaxSize];//数组Data
int Top;//栈顶的位置,数组下标
};
//1.入栈
void Push(Stack PtrS,ElementType item)//PtrS是Stack类型的指针即结构指针/入栈元素item
{
if(PtrS->Top==MaxSize-1){//Top=-1表示栈空
printf("堆栈满");
return;
}
else{
PtrS->Data[++(PtrS->Top)]=item;//item放在Top上面的位置
return;
}
}
//2.出栈
ElementType Pop(Stack PtrS)
{
if(PtrS->Top==-1){
printf("堆栈空");
return ERROR;//ERROR是ElementType的特殊值,标志错误
}
else
return(PtrS->Data[(PtrS->Top)--]);
}
//请用一个数组实现两个堆栈,要求最大地利用数组空间,
//使数组只要有空间入栈操作就可以成功
//分析:一种比较聪明的方法是使用这两个栈分别
//从数组的两头开始向中间生长;当两个栈的栈顶指针
//相遇时,表示两个栈都满了
#define MaxSize<存储数据元素的最大个数>
struct DStack{
ElementType Data[MaxSize];
int Top1;//堆栈1的栈顶指针
int Top2;//堆栈2的栈顶指针
}S;
S.Top1=-1;//堆栈1空的条件
S.Top2=MaxSize;//堆栈2空的条件
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;
}
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)++];
}
}
typedef struct SNode *Stack;
struct SNode{
ElementType Data;
struct SNode *Next;
};
//1.堆栈初始化(建立空栈)
Stack CreateStack()
{//构建一个堆栈的头结点,返回指针
Stack S;
S=(Stack)malloc(sizeof(struct SNode));//申请一个结点
S->Next=NULL;
return S;
}
//2.判断堆栈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=item;
TmpCell->Next=S->Next;
S->Next=TmpCell;
}
//Pop操作
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;//把FirstCell->Element赋值给一个变量,因为要return
free(FirstCell);//释放空间
return TopElem;
}
}