//顺序栈
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#define MaxSize 10
typedef int ElemType;
typedef struct {
ElemType data[MaxSize];
int top;
}SqStack;
bool InitStack(SqStack& S)
{
S.top = -1;//指向当前栈顶元素若=0则指向下一个存储位置
return true;
}
bool StackEmpty(SqStack S)
{
return(S.top == -1);
}
bool Push(SqStack& S, ElemType x)
{
if (S.top == MaxSize - 1)
return false;
S.data[++S.top] = x;
return true;
}
bool Pop(SqStack& S, ElemType& x)
{
if (StackEmpty(S))
return false;
x = S.data[S.top--];
return true;
}
bool GetTop(SqStack S, ElemType& x)
{
if (StackEmpty(S))
return false;
x = S.data[S.top];
return true;
}
bool DestroyStack(SqStack& S)
{
S.top = -1;//顺序栈位于栈区函数结束自动回收
return true;
}
int main()
{
SqStack S;
ElemType e;
InitStack(S);
Push(S, 3);
Push(S, 5);
Push(S, 7);
Pop(S, e);
printf("Pop e=%3d\n", e);
GetTop(S, e);
printf("Get e=%3d\n", e);
Pop(S, e);
printf("Pop e=%3d\n", e);
GetTop(S, e);
printf("Get e=%3d\n", e);
DestroyStack(S);
Pop(S, e);
printf("Pop e=%3d\n", e);
if (Pop(S, e))
printf("Pop e=%3d\n", e);
else
printf("Pop fail\n");
return 0;
}
//共享栈--简易
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#define MaxSize 10
typedef int ElemType;
typedef struct {
ElemType data[MaxSize];
int top0, top1;
}SqShStack;
void InitSqShStack(SqShStack& S)
{
S.top0 = -1;
S.top1 = MaxSize;
}
//应该分开判断左边栈右边栈是否为空此处简写
bool SqShStackEmpty(SqShStack S)
{
if (S.top0 == -1 && S.top1 == MaxSize)
return true;
else return false;
}
bool SqShStackfull(SqShStack S)
{
return (S.top0 + 1 == S.top1);
}
bool Push(SqShStack& S, ElemType e1, ElemType e2)
{
if (SqShStackfull(S)) return false;
S.data[++S.top0] = e1;
S.data[--S.top1] = e2;
return true;
}
bool GetTop(SqShStack S, ElemType& e1, ElemType& e2)
{
if (SqShStackEmpty(S)) return false;
e1 = S.data[S.top0];
e2 = S.data[S.top1];
return true;
}
bool Pop(SqShStack& S, ElemType& e1, ElemType& e2)
{
if (SqShStackEmpty(S)) return false;
e1 = S.data[S.top0--];
e2 = S.data[S.top1++];
return true;
}
bool DestroyStack(SqShStack& S)
{
S.top0 = -1;
S.top1 = MaxSize;
return true;
}
int main()
{
SqShStack S;
InitSqShStack(S);
ElemType e1,e2;
Push(S, 3,-3);
Push(S, 5,-5);
Push(S, 7,-7);
Pop(S, e1,e2);
GetTop(S, e1, e2);
Pop(S, e1, e2);
GetTop(S, e1, e2);
DestroyStack(S);
return 0;
}
栈--顺序栈--共享栈
最新推荐文章于 2023-04-14 09:35:40 发布