大话数据结构——栈的顺序存储结构~2020.6.27

“栈(stack)是限定仅在表尾进行插入和删除操作的线性表。”
栈又称后进先出(LIFO)的线性表,首先它是一个线性表,也就是说,栈元素具有线性关系。
此处直接奉上用数组(封装于类中)实现的线性存储结构栈及双向栈,其中双向栈仅给出了几个必要的类方法,而不包括于主函数中的测试操作。

稍后将奉上链式存储结构栈的代码。

#include <iostream>
#include <cstdio>
using namespace std;
const int maxn=25000;
typedef int ElemType;
class Stack{
 private: 
  ElemType data[maxn+1];
  int top;
 public:
  Stack():top(0) {}
  bool push(ElemType n);
  bool pop(ElemType *element);
  int cnt(){
   return top;
  }
};
bool Stack::push(ElemType n){
 if(top==maxn) return false;
 data[++top]=n;
 return true;
}
bool Stack::pop(ElemType *element){
 if(top==0) return false;
 *element=data[top--];
 return true;
}
int main()
{
 Stack s;//建立栈 
 int randomNumber=100,e=0,counter=0;
 while(randomNumber!=0){
  s.push(randomNumber);
  randomNumber-=5;
 }
 counter=s.cnt();
 //将一个随机数据压入栈中(随意编写的数据,为了说明问题并测试程序)
 //查看栈中数据
 while(s.pop(&e)){
  cout<<"这是栈中的第"<<counter-s.cnt()<<"个数据,数据值为:"<<e<<"栈中剩余数据个数:"<<s.cnt()<<endl; 
 } 
 return 0;
}

以下为双向栈的部分代码,其中仅给出了几个必要的类方法,而不包括主函数

#include <iostream>
#include <cstdio>
using namespace std;
const int maxn=25000;
typedef int ElemType;
class Stack{
 private: 
  ElemType data[maxn+1];
  int top1,top2;
 public:
  Stack():top1(0),top2(0) {}
  bool push1(ElemType n);
  bool push2(ElemType n);
  bool pop1(ElemType *element);
  bool pop2(ElemType *element);
  int cnt1(){
   return top1;
  }
  int cnt2(){
   return top2;
  }
};
bool Stack::push1(ElemType n){
 if(top1+1>=top2) return false;
 data[++top1]=n;
 return true;
}
bool Stack::pop1(ElemType *element){
 if(--top1==0) return false;
 element=data[top1--];
 return true;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值