1.随机产生10个100以内的整数建立一个顺序表,显示该顺序表中的数据元数;
2.随机产生10个100以内的整数建立一个顺序表,显示该顺序表中的数据元数,随机产生1-10中的任意整数 p ,在顺序表中查找第 p 个元素,并显示该元素值;
3.随机产生10个100以内的整数建立一个顺序表,显示该顺序表中的数据元数,输入顺序表中任一元素,查找并显示该元素在顺序表中的位置;
4.随机产生10个100以内的整数建立一个顺序表,显示该顺序表中的数据元数,将33插入到第3个元素位置,并显示更新后的顺序表;
5.随机产生10个100以内的整数建立一个顺序表,显示该顺序表中的数据元数,输入顺序表中任一元素,删除该元素,并显示更新后的顺序表;
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int MaxSize = 100;//全局变量
template <typename DataType>
class Seqlist//定义一个顺序表的类
{
private:
DataType data[MaxSize];
int length;
public:
Seqlist() :length(0) {}//初始化长度为0
Seqlist(DataType a[], int n)//形参a[]来给data[]赋值,n,数组的长度
{
for (int i = 0; i < n; i++)
{
data[i] = a[i];
}
length = n;
}
~Seqlist() {}//析构函数
int Length() { return length; }
int Get(int i) { return data[i]; }
int Locate(DataType x)//顺序表的查找
{
for (int i = 0; i < length; i++)
{
if (data[i] == x)
return i;
}
return -1;//若没有找到,返回-1
}
void insert(int i, DataType x)//在顺序表中插入一个新元素;i为所插入值为x在数组中的下标
{
if (i<0 || i>length)//因为是插入一个元素,所以不用加等号,元素可以插在最后
throw "Insert position out of range!";//判断i值是否超出所允许的范围
for (int j = length; j > i; --j)
{
data[j] = data[j - 1];//让原数组中下标为i及之后的数从后往前依此后移一个
}
data[i] = x;
++length;
}
int Delete(int i)//在顺序表中删除一个指定的元素,i为所删除的值在数组中的原下标
{
if (i < 0 || i >= length)//判断i值是否超出所允许的范围;若不加等号,会删除一个本就不存在的数,会报错
{
throw"Delete position out of range!";
}
int temp = data[i];//定义一个变量,来储存被删除的元素的值
for (int j = i; j < length - 1; ++j)//数组的下标从0开始变化,将下标为i+1及之后的元素依次从前向后前移一个,覆盖掉原下标为i的值
{
data[j] = data[j + 1];
}
--length;//删除一个元素后,长度减1
return temp;
}
bool Empty() { return length == 0; }//判断顺序表是否为空
void PrintList()//打印顺序表
{
for (int i = 0; i < length; ++i)
cout << data[i] << " ";
cout << endl;
}
};
int main()
{
srand(static_cast<unsigned int>(time(nullptr)));
Seqlist<int> list; // 创建一个空的顺序表对象
// 生成10个100以内的随机数并添加到顺序表中
for (int i = 0; i < 10; i++) {
int randomValue = rand() % 100; // 生成0到99之间的随机数
list.insert(list.Length(), randomValue); // 将随机数插入顺序表的末尾
}
list.PrintList(); // 打印顺序表中的所有元素
cout << "原始顺序表";
list.PrintList();
int insertpos; //要插入元素在数组中的下标
int insertValue;//要插入的值
cout << "请输入要插入的下标" << endl;
cin >> insertpos;
cout << "请输入要插入的值" <<endl;
cin >> insertValue;
list.insert(insertpos, insertValue);//调用插入函数
cout << "After inserting " << insertValue << "at position" << insertpos << ": ";
list.PrintList();
int indexposvalue = list.Get(0);
cout << "打印顺序表的第一个元素" << indexposvalue;
cout << endl;
int cz;
cout << "请输入要查找的数" << endl;
cin >> cz;
int locationByValue = list.Locate(cz);//查找数组中是否有值为444;调用查找函数
if (locationByValue == -1)
{
cout << "该顺序表中没有该值" << endl;
}
else
{
cout << "查找成功" << endl;
}
int d1, dn;
cout << "请输入要删除的数的下标" << endl;
cin >> d1;
cout << "请输入要删除的数" << endl;
cin >> dn;
if (list.Delete(d1) == dn)
{
cout << "删除成功" << endl;
}
else
{
cout << "删除失败" << endl;
}
return 0;
}