代码改变世界

数据结构——线性表

2016-01-30 10:38  迷你天才  阅读(217)  评论(0编辑  收藏  举报

线性表的顺序结构 ——顺序表

顺序表中数据元素的存储地址是其序号的线性函数 只要确定了存储顺序的起始地址 计算任意一个元素的存储地址的时间是相等的 所以这种存储结构称为随机存储

 

顺序表得实现(模板实现)

#include<iostream>
using namespace std;
const int MaxSize = 100;
template<class DataType>            //类模板
class SeqList {
private:
 int length;                       //线性表长度
 DataType data[MaxSize];            //存放数据元素的数组
public:
 SeqList() { length = 0 };            //无参构造函数 数组长度为零
 SeqList( DataType a[],int n );           //有参构造函数 建立一个长度为n的顺序表
 ~SeqList() {};                   //析构函数
 int Length() { return length; };        //求线性表长度
 DataType Get(int i);               //按位查找,线性表中第i个元素
 int Locate(DataType x);             //按值查找,在线性表中查找x元素在数组中的位置
 void Insert(int i, DataType x);        //插入元素,在线性表中第i个位置插入元素x
 DataType Delect(int i);              //删掉线性表的第i个元素
 void PrintList();                  //遍历操作,按照序号依次输出
};

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

template<class DataType>
DataType SeqList<DataType>::Get(int i){
 if (i<1 || i>length)
  cout << "参数非法";
 else
  cout << data[i - 1];
 return 0;
}

template<class DataType>
int SeqList<DataType>::Locate(DataType x){
 for (int i = 0; i < n; i++)
  if (data[i] = x)
   cout << i + 1;
  else
   cout<<"查找失败";
 return 0;
}

template<class DataType>
void SeqList<DataType>::Insert(int i, DataType x) {
 if (length >= MaxSize)cout << "上溢";
 if (i < 1 || i>length)cout << "位置";
 for (int j = length; j >= i; j--)
  data[j] = data[j - 1];
 data[i - 1];
 length++;
}

template<class DataType>
DataType SeqList<DataType>::Delect(int i){
 if (length == 0)cout << "下溢";
 if (i<1 || i>length)cout << "位置";
 x = data[i - 1];
 for (j = i; j < length; j++)
  data[j - 1] = data[i];
 length--;
 return x;
}

template<class DataType>
void SeqList<DataType>::PrintList(){
 for (int i = 0; i < length; i++)
  cout << data[i];
}