1002: 顺序表(2)
1002: 顺序表(2)
Description
已知一个有序顺序表类SortList及main函数的部分代码如下,请完成SortList类的成员函数Insert和DispList,得到对应的运行结果,勿改动main函数。注意:插入函数Insert效率为O(n),不能利用排序算法实现。
//有序表类
template <class T>
class SortList
{
public:
SortList() { length = 0; } // 置空表
~SortList() {}
void Insert(T x); // 非递减有序表的插入x,使序列仍有序
void DispList(); // 输出表
private:
T data[MaxSize]; // 存储元素
int length; // 顺序表实际长度
};
// 构造有序表A:函数声明
template <class T>
void CreateSort(SortList<T> &A);
// 主函数
int main()
{
SortList<int> A; // 整型数据表A
// 生成一个有序表A
CreateSort(A);
SortList<char> B; // 字符型数据表B
CreateSort(B);
A.DispList();
B.DispList();
return 0;
}
// 构造有序表A:函数定义
template <class T>
void CreateSort(SortList<T> &A)
{
int i, n;
T x;
cin >> n;
for (i = 1; i <= n; i++)
{
cin >> x;
try
{
A.Insert(x);
}
catch (const char *wrong)
{
cout << wrong << endl;
}
}
}
Input
数据输入说明:下列两行输入分别代表创建A表和B表,元素分别为整型和字符型,每行输入中第一个值为元素个数,之后为待插入的各个数据。
5 3 24 23 2 6
4 abnf
Output
输出数据用空格隔开,且结果为元素的有序序列。
Sample Input
5 3 24 23 2 6
4 abnf
Sample Output
The length:5
The elements:
2 3 6 23 24
The length:4
The elements:
a b f n