顺序栈的表示和实现(一个完整的例子)
#include<bits/stdc++.h>
using namespace std;
#define MAXSIZE 100
typedef int ElemType;
typedef int Statue;
typedef struct {
ElemType data[MAXSIZE] ;
int top;
} SqStack;
void InitStack(SqStack &S);
bool StackEmpty(SqStack S);
bool Push(SqStack &S,ElemType x);
bool Pop(SqStack &S,ElemType &e);
bool GetTop(SqStack S, ElemType &e);
Statue StackLength(SqStack S);
void Print_s(SqStack S);
int main() {
SqStack s;
InitStack(s);
Push(s,5);
Push(s,1);
Push(s,8);
Print_s( s);
int e;
Pop(s,e);
cout<<"出栈"<<e<<endl;
Print_s(s);
cout<<StackEmpty(s)<<endl;
}
void Print_s(SqStack S) {
while(S.top!=-1) {
cout<<S.data[S.top--];
}
cout<<endl;
}
Statue StackLength(SqStack S) {
return ++S.top;
}
bool GetTop(SqStack S, ElemType &e) {
if(S.top==-1)
return false;
e = S.data[S.top];
return true;
}
bool Pop(SqStack &S,ElemType &e) {
if(S.top==-1)
return false;
e=S.data[S.top--];
return true;
}
bool Push(SqStack &S,ElemType x) {
if(S.top==MAXSIZE-1)
return false;
S.data[++S.top]=x;
return true;
}
bool StackEmpty(SqStack S) {
if(S.top==-1)
return true;
else
return false;
}
void InitStack(SqStack &S) {
S.top = -1 ;
}
链栈
//存储结构
typedef struct Linknode{
ElemType data; //数据域
struct Linknode *next; //指针域
}*LinkStack,StackNode;
//链栈入栈,相当于链表的头插法
Status Push(LinkStack &s,SElemType e){
p = new StackNode; //生成一个新节点
p->data = e;
p->next=s;
s=p;
return ok;
}
//链栈的出栈
Status Pop(LinkStack &s,SElemType &e){
//删除栈顶元素,用e返回其值
if(s==null) return error; //栈空
e=s->data;
p=s;
s=s->next;
delete p;
return ok;
}
共享栈