堆栈顺序存储的实现
typedef struct SNode *Stack;
struct SNode
{
ElementType Data[MaxSize];
int Top;
};
入栈
void Push(Stack PtrS,Element Item)//入栈
{
if(PtrS->Top==MaxSize-1)
{
printf("堆栈满");return;
}
else
{
PtrS->Data[++(PtrS->Top)]=Item;
return;
}
}
出栈
Element Pop(Stack PtrS)//出栈
{
if(PtrS->Top==-1)
{
printf("堆栈空");return;
}
else
{
return (PtrS->Data[(PtrS->Top)--]);//注意这里的减号的位置不要弄错了
}
}
例题
请用一个数组实现两个堆栈,要求最大地利用数组空间,使数组只要有空间入栈操作就可以成功。
#define MaxSize
struct DStack
{
ElementType Data[MaxSize];
int Top1;
int Top2;
}S;
S.Top1=-1;
S.Top2=MaxSize;
入栈
void Push(struct DStack *PtrS,ElementType Item,int Tag)//入栈
{
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)
{
if (Tag==1)
{
if (PtrS->Top1==-1)
{
printf("堆栈满");return NULL;
}
else
return PtrS->Data[(Ptrs->Top1)--];
}
else
{
if (PtrS->Top2==MaxSize)
{
printf("堆栈满");
}
else
return PtrS->Data[(Ptrs->Top2)++];
}
}
堆栈的链式存储实现
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)//判断是否为空
{
return (s->Next==NULL);
}
void Push(Stack s,ElementType Item)//入栈
{
struct Stack *TmpCell;
TmpCell=(Stack)malloc(sizeof(struct Stack));
TmpCell->ElementType=Item;
TmpCell->Next=s->Next;
s->Next=TmpCell;
}
ElementType Pop(Stack s)//取出栈顶元素
{
struct Stack *FirstCell;
ElementType Item;
if (IsEmpty(s))return NULL;
else
{
FirstCell=s->Next;
s->Next=FirstCell->Next;
Item=FirstCell->Data;
free(FirstCell);
return Item;
}
}