目录
一、顺序栈
1.结构体
typedef struct{
ElemType data[MaxSize];
int top;
}SqStack;
2.操作函数
1)顺序栈的初始化
bool InitStack(SqStack &s)
{
s.top =-1;
}
2)判空
bool StackEmpty(SqStack s)
{
return s.top==-1;
}
3)进栈
bool push(SqStack &s, ElemType1 e)
{
if(s.top==MaxSize-1) //如果栈满
return false;
s.data[++s.top] = e;
return true;
}
4)出栈
bool pop(SqStack &s, ElemType1 &e)
{
if(StackEmpty(s))
return false;
e=s.data[s.top--];
return true;
}
5)获取栈顶元素,用e返回
bool GetTop(SqStack &s, ElemType1 &e)
{
if(StackEmpty(s))
return false;
e=s.data[s.top];
return true;
}
二、链栈
1.结构体
typedef struct LinkNode{
ElemType data;
LinkNode *next;
}LinkNode,*LinkStack;
2.功能函数
1)初始化链栈
bool InitLinkStack(LinkStack &ls)
{
ls=(LinkNode*)malloc(sizeof (LinkNode));
ls->data=NULL;
ls->next=NULL;
return true;
}
2)判断栈空
bool LinkStackEmpty(LinkStack ls)
{
return ls->next==NULL;
}
3)进栈
bool push(LinkStack &s, ElemType e)
{
LinkNode *NewNode = (LinkNode*)malloc(sizeof(LinkNode));
NewNode->data=e;
NewNode->next=s->next; //类似于头插法
s->next=NewNode;
return true;
}
4)出栈,用e返回出栈元素
bool pop(LinkStack &s, ElemType &e)
{
if(LinkStackEmpty(s))
return false;
LinkNode *p = s->next;
e=p->data;
s->next = p->next;
free(p);
return true;
}
5)获取栈顶元素值,用e返回
bool GetTop(LinkStack s, ElemType &e)
{
if(LinkStackEmpty(s))
return false;
e=s->next->data;
return true;
}
三、共享栈
1.结构体
typedef struct{
ElemType data[MaxSize];
int top0;
int top1;
}ShareStack;
2.功能函数
1)初始化共享栈
bool InitShareStack(ShareStack &ss)
{
ss.top0=-1;
ss.top1=MaxSize;
}
2)0号栈判空
bool Stack0Empty(ShareStack ss)
{
return ss.top0==-1;
}
3)1号栈判空
bool Stack1Empty(ShareStack ss)
{
return ss.top1==MaxSize;
}
4)0号栈入栈
bool push0(ShareStack &ss,ElemType e)
{
if(ss.top0+1==ss.top1) //判断栈满
return false;
ss.data[++ss.top0] = e;
return true;
}
5)1号栈入栈
bool push1(ShareStack &ss, ElemType e)
{
if(ss.top1-1==ss.top0) 判断栈满
return false;
ss.data[--ss.top1]=e;
return true;
}
6)0号栈出栈
bool pop0(ShareStack &ss, ElemType &e)
{
if(Stack1Empty(ss))
return false;
e=ss.data[ss.top0--];
return true;
}
7)1号栈出栈
bool pop1(ShareStack &ss, ElemType &e)
{
if(Stack2Empty(ss))
return false;
e=ss.data[ss.top1++];
return true;
}