数据结构笔记之栈

栈:只允许在一端进行插入或删除的线性表
栈顶:栈中允许插入和删除的一端。
栈底:固定的,不允许进行插入和删除的另一端。

栈的特点:
1.栈是受限的线性表,具有线性关系。
2.先进后出(FILO)
顺序栈的定义

#define MAXSIZE 50    //定义栈中元素的最大个数
typedef struct{
   ElemType data[MAXSIZE];     //存放栈中元素
   int top;        //栈顶指针
}SqStack;

空栈的判定条件通常定为top=-1,满栈的判定条件通常为top==MAXSIZE-1,栈中数据元素个数为top+1。

顺序栈的操作:
1.判空

bool StackEmpty(SqStack S){
if(s.top==-1)  return false;
else    return true;
}

2.进栈

bool Push(Sqstack &s,ElemType x){
if(s.top==MAXSIZE-1)   return false;
s.data[++top]=x;
return true;
}

3.出栈

bool Pop(SqStack &s, ElemType &x){
if(s.top==-1)  return false;
x=s.data[s.top--];
return true;
}

4.读取栈顶元素

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;  //栈1栈顶指针
int top2;  //栈2栈顶指针
}SqDoubleStack;

共享栈的进栈操作:

bool Push(SqDoubleStack &S,ElemType x,int StackNum){
if(S.top1+1==S.top2)  return false;   //栈满
if(StackNum==1)  S.data[++top1]=x;  //栈1有元素进栈
else if(StackNum==2)   S.data[--top2]=x;  //栈2有元素进栈
return true;
}

链式栈:
栈的链式存储结构也叫作链栈。
链栈的定义:

typedef struct SNode{
ElemType data;  //数据域;
struct SNode *next;    //指针域;
}SNode, *SLink;
typedef struct LinkStack{
SLink top;   //栈顶指针
int count;   //链栈结点书
}LinkStack;

空栈的判定条件通常定为top==NULL;

链栈的操作
1.入栈:

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;
}

2.出栈

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(p);
s->count--;
return true;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值