已知顺序表类的定义如下,实现各个成员函数。主函数中输入数据(以0结束)利用Insert函数依次将数据插入到表的1号位置,利用DispList按照逻辑次序输出表中元素,再输入一个要查找的元素,利用查找函数Locate查找其在表中的位置,最后利用Reverse函数将数据逆序,再利用DispList输出。 template <typename DataType> class SeqList { public: SeqList(); //构造函数,将表置空 ~SeqList(){} //析构 int Locate(DataType x); //查找元素x在表中的位置,成功返回x在表中的位置,否则返回0 void Insert(int i, DataType x); //在表的i位置插入元素x void Reverse(); //逆序表中数据 void DispList(); private: DataType data[MaxSize]; //存储元素 int length; //顺序表实际长度 };
时间: 2025-03-10 11:08:36 浏览: 113
好的,下面是一个完整的顺序表类 `SeqList` 的实现,并包含您提到的功能:
```cpp
#include <iostream>
using namespace std;
const int MaxSize = 100; // 定义最大容量
template<typename DataType>
class SeqList {
public:
SeqList(); // 构造函数,初始化为空表
~SeqList() {} // 析构函数,默认即可
int Locate(DataType x); // 查找元素x的位置,找到返回位置索引(从1开始),未找到返回0
void Insert(int i, DataType x); // 在第i个位置插入元素x
void Reverse(); // 将表内元素逆序排列
void DispList(); // 按照逻辑次序输出所有元素
private:
DataType data[MaxSize]; // 存储数组
int length; // 当前长度
};
// 初始化构造函数
template<typename DataType>
SeqList<DataType>::SeqList(): length(0) {}
// 实现Locate查找操作
template<typename DataType>
int SeqList<DataType>::Locate(DataType x){
for (int i=0;i<this->length;++i)
if(this->data[i] == x)
return i+1; // 返回位置(注意:这里的下标是从1开始计数)
return 0; // 如果找不到就返回0表示不存在该值
}
// 插入新节点到指定位置
template<typename DataType>
void SeqList<DataType>::Insert(int i, DataType x){
if(length >= MaxSize || i > this->length + 1 || i <= 0){ // 参数检查
cout << "Error: Invalid position or list full" << endl;
return ;
}
if(i>this->length){
this->data[this->length++]=x;
return;
}
for (int j=length;j>=i ;--j )
this->data[j]=this->data[j-1];
this->data[i - 1] = x;
++this->length;
}
// 翻转链表中的元素
template<typename DataType>
void SeqList<DataType>::Reverse(){
for(int front=0,end=this->length-1;front<=end;front++,end--){
swap(data[front], data[end]);
}
}
// 输出当前列表的所有内容
template<typename DataType>
void SeqList<DataType>::DispList(){
if(!this->length){
cout<<"The sequence is empty."<<endl;
return;
}
for(int k=0;k<this->length;++k)
cout<<this->data[k]<<" ";
cout<<endl;
}
```
接下来给出主程序部分,用于测试上述功能:
```cpp
int main()
{
SeqList<int> L;
int value;
while(true){
cin >> value;
if(value==0) break;
else L.Insert(1,value);
}
cout<<"\nOriginal List:"<<endl;
L.DispList();
cout<<"\nEnter a element to locate:";
cin>>value;
int pos=L.Locate(value);
cout<<"\nThe location of the element "<<value<<" in the table is at position "
<<pos<<(pos?"":"\t(Note: Not Found)")<<endl;
L.Reverse();
cout<<"\nAfter reversing the order, the new list becomes:" << endl;
L.DispList();
return 0;
}
```
以上代码实现了基于模板类的基本顺序表及其基本操作,包括但不限于插入、查询以及反转等功能。
阅读全文
相关推荐

















