Realization of Data Structure C++ Sequence Table and Related Operations

Implementation of the sequence table

const int MaxSize=100                  //根据实际问题具体定义
template<typename DataType>            //定义模板类SeqList
class SeqList
{
    
    
public:
   SeqList();                       //建立空的顺序表
   SeqList(DataType a[],int n);       //建立长度为n的顺序表
   ~SeqList();                        //析构函数
   int Length();                   //求线性表的长度
   DataType Get(int i);              //按位查找,查找第i位的元素的值
   int Locate(DataType x);           //按值查找,查找值为x的元素的序号
   void Insert(int i,DataType x); //插入操作,在第i位插入值为x的元素
   DataType Delete(int i);           //删除操作,删除第i位的元素
   int Empty();                      //判断线性表是否为空
private:
   DataType data[MaxSize];           //存放数据元素的数组
   int length;                       //线性表的长度
}

1. No parameter constructor - initialization sequence table

Just initialize the length of the sequence table to 0.

2. Constructor with parameters - create a sequence table

template<typename DataType>
SeqList<DataType>::SeqList(DataType a[],int n)
{
    
    
 if(n>MaxSize)
 throw "非法参数";
 for(int i=0;i<n;i++)
     data[i]=i;
 length=n;
 }    

3. Destructor - Destroy the sequence table

The sequence table automatically releases space, so there is no need to destruct, and the destruct is empty.

4. Null operation

You only need to judge whether the Length is 0.

5. Find the length of the sequence table

Just look at the value of length

6. Traverse operation

template<typename DataType>
void SeqList<DataType>::PrintList()
{
    
    
 for(int i=0;i<length;i++)
   cout<<data[i]<<"\t";               //依次输出线性表的元素值
 cout<<endl;
}  

7. Bitwise search

template<typename DataType>
DataType SeqList<DataType>::Get(int i)
{
    
    
  if(i<1 || i>length)
  throw "查找非法位置";
  else
  return data[i-1];
}  
  

8. Find by value

template<typename DataType>
int SeqList<DataType>::Locate(DataType x)
{
    
    
 for(int i=0;i<length;i++)
   if(data[i]==x)
     return i+1;
   else
     return 0;
}  

9. Insert operation

template<typename DataType>
void SeqList<DataType>::Insert(int i,DataType x)
{
    
    
  if(i<1 || i>length+1)
  throw "插入位置错误";
  if(length == MaxSize)
  throw "上溢";
  for(int j = length;j>=i;j--)     //将最后一个元素直至第i个元素分别向后移一个位置
      data[j] = data[j-1];
   data[i-1] = x;
   length++;
}         

10. Delete operation

template<typename DataType>
DataType SeqList<DataType>::Delete(int i)
{
    
    
  DataType x;
  if(length==0)
  thorow "下溢";
  if(i<1 || i>length)
  throw "删除位置错误";
  x=data{
    
    i-1];
  for(int j=i;j<length;j++)
     data[j-1]=data[j];
  length--;
  return x;
}   

Guess you like

Origin blog.csdn.net/qq_51344334/article/details/114446433