定义:栈是一种只能在表的一端进行插入或删除操作的线性表
总结约定:
1.top总是指向栈顶元素,初始值为-1
栈空条件:top=-1
栈满条件:top=MaxSize-1
进栈操作:进栈时top增加1,既top++,再将元素入栈
出栈操作:先从top处将元素取出,再将top-1,既top–
//栈的顺序存储结构
#define MaxSize 10
typedef struct{
ElemType data[MaxSize];
int top; //top为栈顶
}sqstack;
//在顺序栈中实现栈的基本运算
//1.初始化栈initstack(&s)
void initstack(sqstack *&s){
s=(sqstack *)macllo(sizeof(sqstacke));
s->top=-1;
}
//2.销毁栈
void Destroystack(&s){
free(s);
}
//3.判断栈是否为空stackEmpty(s)
bool stackEmpty(sqstack *s){
return (s->top==-1);
}
//4.进栈push(&s,e)
bool push(sqstack *&s,ElemType e){
if(s->top==MaxSize-1) return false;
s->top++;
s->data[s->top]=e;
return true;
}
//5.出栈pop(&s,e)
bool pop(sqstack *&s,ElemType &e){
if(s->top==-1) return false;
e=s->data[s->top];
s->top--;
return true;
}
//6.取栈顶元素GetTop(s,&e)
bool GetTop(sqstack *s,ElemType &e){
if(s->top==-1) return flase;
e=s->data[s->top];
return true;
}
栈的链式存储结构
链栈的四要素:
1.栈空条件:s->next=NULL
2.栈满:不考虑
3.进栈e操作:将包含e的结点插入到头节点后
4.退栈操作:取出头节点之后结点的元素并删除之
s->next=s->next->next
链栈的结构类型:
typedef strcut linknode{
ElemTyep data;
struct linknode *next;
}LinkStnode;
//链栈实现的基本运算
1.初始化栈initstack(&s)
void(LinkStnode *&s){
s=(LinkStnode *)malloc(sizeof(linkstnode));
s->next=NULL;
}
2.销毁栈Destroystack(&s)
void destroystack(LinkstNode *&s){
LinkStnode *p=s,*q=s->next;
while(q!=NULL){
free(p);
p=q;
q=p->next;
}
}
3.判断是否为空栈stackEmpty(s)
bool stackEmpty(LinkStnode *s){
return (s->next==NULL);
}
4.进栈push(&s,e)
void push(LinkStnode *s,ElemType e){
LinkStnode *p;
p=(LinkStnode *)mallo(sizeof(LinkStnode));
p->data=e;
p->next=s->next;
s->next=p;
}
5.出栈pop(&s,&e)
bool pop(LinkStnode *s,ElemType &e){
LinkStnode *p;
if(s->next==NULL) return flase;
p=s->next;
e=p->next;
s->next=p->next;
free(p);
retrun true;
}
6.取出栈顶元素GetTop(&s,&e){
bool GetTop(LinkStnode *s,ElemType &e){
if(s->next==NULL) return false;
e=s->next->data;
return true;
}
}
运算规则:后进先出