用程序表达的有隔断的盒子——线性表(C++)


注:图片资源来自于互联网

为什么把线性表比喻成一个有隔断的盒子?
它有一块连续的存储空间,不管从左边用还是从右边用都有唯一的“第一个格子”和“最后一个格子”,除了两头的格子,其他的都紧挨着两个格子。

线性结构的基本特征:
1.集合中必存在唯一的一个"第一元素";
2.集合中必存在唯一的一个"最后元素";
3.除最后元素在外,均有唯一的后继;
4.除第一元素之外,均有唯一的前驱。

  1. template<class ElemType>
  2. class seqlist
  3. {
  4. private:
  5.     ElemType* sl_;
  6.     int slsize_;                                 //线性表大小
  7.     int currsize_;                               //插入元素的个数 
  8. public:
  9.     seqlist(int size);
  10.     ~seqlist();
  11.     bool Insert(int pos,ElemType item);         //插入   pos > 0
  12.     bool Delete(int pos);                       //删除   pos > 0
  13.     inline int length(){return slsize_;};      //返回线性表大小
  14.     inline int size(){return currsize_;};      //返回已填入元素的大小
  15.     ElemType* get(int pos);                      //pos  > 0 
  16.     int location(ElemType elem);
  17. };
  18. template<class ElemType>
  19. seqlist<ElemType>::seqlist(int size)
  20. {
  21.     sl_ = new ElemType[size];
  22.     slsize_ = size;
  23.     currsize_ = 0;
  24. }
  25. template<class ElemType>
  26. seqlist<ElemType>::~seqlist()
  27. {
  28.     delete [] sl_; 
  29. }
  30. template<class ElemType>
  31. bool seqlist<ElemType>::Insert(int pos,ElemType item)
  32. {
  33.     if(pos > 0  && pos <= currsize_ && currsize_ < slsize_)
  34.     {
  35.         for(int i = currsize_; i >= pos; i--)
  36.         {
  37.             sl_[i] = sl_[i-1]; 
  38.         }
  39.         sl_[pos - 1] = item;
  40.         currsize_ += 1;
  41.         return true;
  42.     }
  43.     else
  44.         return false;
  45. }
  46. template<class ElemType>
  47. bool seqlist<ElemType>::Delete(int pos)
  48. {
  49.     if(pos > 0 && pos <= currsize_)
  50.     {
  51.         for(int i = pos; i <= currsize_; i++)
  52.         {
  53.             sl_[i-1] = sl_[i];
  54.         }
  55.         currsize_ -= 1; 
  56.         return true;
  57.     }
  58.     else
  59.         return false;
  60. }
  61. template<class ElemType>
  62. ElemType* seqlist<ElemType>::get(int pos)
  63. {
  64.     if(pos > 0 && pos <= currsize_)
  65.     return &sl_[pos-1];
  66.     else return NULL;
  67. }
  68. template<class ElemType>
  69. int seqlist<ElemType>::location(ElemType elem)
  70. {
  71.     for(int i = 0; i < currsize_; i++)
  72.     {
  73.         if(elem == sl_[i])
  74.             return i+1;
  75.     }
  76.     return -1;
  77. }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值