顺序栈
#define Maxsize 50 //define the max size of the stack
typedef struct
{
Elemtype data[Maxsize];// store the element of the stack
int top;//
}SqStack;
1.Top值不能超过maxsize
2.空栈的判定条件通常为top==-1,满栈的判定条件通常为top==maxsize-1,,栈中数据元素个数为top+1
判空操作:
bool StackEmpty(SqStack S){
if (s.top==-1) return true;
else return false;
}
进栈:
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 (S.top==-1)return false;
x=S.data[S.top--];
return true;
}
读取栈顶元素:
bool GetTop(SqStack S,ElemType &x){
if (s.top==-1) return false;
x=S.data[S.top];
return true;
}
共享栈
#define Maxsize 100
typedef struct{
Elemtype data[Maxsize];
int top1;
int top2;
}SqDoubleStack;
进栈
bool Push(SqDoubleStack &S,ElemType x,int stackNum)
{
if (S.top1+1==s.top2) return false;//stack is full;
if (stackNum==1) S.data[++S.top1]=x;//stack 1 has elements to come in;
else if(stackNum==2) S.data[--top2]=x;
return true;
}
出栈
bool Pop(SqStack &S,Elemtype &x,int stackNum)
{
if(stackNum==1)
{
if (S.top1==-1)return false;
x=S.data[S.top1--];
return true;
}
else
{
if(S.top2==Maxsize-1)return false;
x=S.data[S.top2--];
return false;
}
}
链式栈
typedef struct SNode{
Elemtype data;//
struct SNode *next;
}SNode,*SLink;
typedef struct LinkStack{
SLink top;
int count;
}LinkStack;
进栈
bool Push(LinkStack *S,ElemType x)
{
SLink p=(SLink)malloc(sizeof(SNode));
p->data=x;
p->next=S->top;
S->top=p;
S->count++;
return true;
}
出栈
bool Pop(LinkStack *S,ElemType &x)
{
if (s->top==NULL) return false;
x=S->top->data;
SLink p=S->top;
S->top=S->top->next;
free§;
S->count–;
return true;
}