注:图片资源来自于互联网
为什么把线性表比喻成一个有隔断的盒子?
它有一块连续的存储空间,不管从左边用还是从右边用都有唯一的“第一个格子”和“最后一个格子”,除了两头的格子,其他的都紧挨着两个格子。
线性结构的基本特征:
1.集合中必存在唯一的一个"第一元素";
2.集合中必存在唯一的一个"最后元素";
3.除最后元素在外,均有唯一的后继;
4.除第一元素之外,均有唯一的前驱。
- template<class ElemType>
- class seqlist
- {
- private:
- ElemType* sl_;
- int slsize_; //线性表大小
- int currsize_; //插入元素的个数
- public:
- seqlist(int size);
- ~seqlist();
- bool Insert(int pos,ElemType item); //插入 pos > 0
- bool Delete(int pos); //删除 pos > 0
- inline int length(){return slsize_;}; //返回线性表大小
- inline int size(){return currsize_;}; //返回已填入元素的大小
- ElemType* get(int pos); //pos > 0
- int location(ElemType elem);
- };
- template<class ElemType>
- seqlist<ElemType>::seqlist(int size)
- {
- sl_ = new ElemType[size];
- slsize_ = size;
- currsize_ = 0;
- }
- template<class ElemType>
- seqlist<ElemType>::~seqlist()
- {
- delete [] sl_;
- }
- template<class ElemType>
- bool seqlist<ElemType>::Insert(int pos,ElemType item)
- {
- if(pos > 0 && pos <= currsize_ && currsize_ < slsize_)
- {
- for(int i = currsize_; i >= pos; i--)
- {
- sl_[i] = sl_[i-1];
- }
- sl_[pos - 1] = item;
- currsize_ += 1;
- return true;
- }
- else
- return false;
- }
- template<class ElemType>
- bool seqlist<ElemType>::Delete(int pos)
- {
- if(pos > 0 && pos <= currsize_)
- {
- for(int i = pos; i <= currsize_; i++)
- {
- sl_[i-1] = sl_[i];
- }
- currsize_ -= 1;
- return true;
- }
- else
- return false;
- }
- template<class ElemType>
- ElemType* seqlist<ElemType>::get(int pos)
- {
- if(pos > 0 && pos <= currsize_)
- return &sl_[pos-1];
- else return NULL;
- }
- template<class ElemType>
- int seqlist<ElemType>::location(ElemType elem)
- {
- for(int i = 0; i < currsize_; i++)
- {
- if(elem == sl_[i])
- return i+1;
- }
- return -1;
- }