题目描述

已知一个有序顺序表类SortList及main函数的部分代码如下,请完成SortList类的成员函数Insert和DispList,得到对应的运行结果,勿改动main函数。注意:插入函数Insert效率为O(n),不能利用排序算法实现。
//有序表类
template
class SortList{
public:
SortList(){length=0;} //置空表
~SortList(){}
void Insert(T x); //非递减有序表的插入x,使序列仍有序
void DispList(); //输出表
private:
T data[MaxSize]; //存储元素
int length; //顺序表实际长度
};
//构造有序表A:函数声明
template
void CreateSort(SortList &A);
//主函数
int main(){

SortList A; //整型数据表A
//生成一个有序表A
CreateSort(A);
SortList B; //字符型数据表B
CreateSort(B);
A.DispList();
B.DispList();
return 0;
}

//构造有序表A:函数定义
template
void CreateSort(SortList &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< }
}
}

输入

数据输入说明:下列两行输入分别代表创建A表和B表,元素分别为整型和字符型,每行输入中第一个值为元素个数,之后为待插入的各个数据。
5 3 24 23 2 6
4 abnf

输出

输出数据用空格隔开,且结果为元素的有序序列。

样例输入

5 3 24 23 2 6
4 abnf

样例输出

The length:5
The elements:
2 3 6 23 24
The length:4
The elements:
a b f n

提示

来源

提交

  1. import java.util.Scanner;
  2. class SqList {
  3. private Object[] listElem;
  4. private int curLen;
  5. private String type;
  6. public SqList(int maxSize,String type) {
  7. curLen = 0;
  8. listElem = new Object[maxSize];
  9. this.type = type;
  10. }
  11. public int length() {
  12. return curLen;
  13. }
  14. public void insert(Object x) throws Exception {
  15. if (curLen == listElem.length)
  16. throw new Exception("顺序表已满");
  17. int i;
  18. for(i = 0;i<curLen;i++){
  19. if(type.equals("int")){
  20. if((int)listElem[i]>(int)x)break;
  21. }else{
  22. if((char)listElem[i]>(char)x)break;
  23. }
  24. }
  25. for (int j = curLen; j > i; j--)
  26. listElem[j] = listElem[j - 1];
  27. listElem[i] = x; // 插入 x
  28. curLen++; // 表长加1
  29. }
  30. public void display() {
  31. System.out.println("The elements:");
  32. for (int j = 0; j < curLen; j++) {
  33. System.out.print(listElem[j]+ " ");
  34. }
  35. System.out.println();
  36. }
  37. }
  38. public class Main {
  39. public static void main(String[] args) {
  40. Scanner sc = new Scanner(System.in);
  41. SqList A ;
  42. int l = sc.nextInt();
  43. A = new SqList(l,"int");
  44. for (int i = 0; i < l; i++) {
  45. try {
  46. A.insert(sc.nextInt());
  47. } catch (Exception e) {
  48. e.printStackTrace();
  49. }
  50. }
  51. SqList B;
  52. l = sc.nextInt();
  53. B = new SqList(l,"char");
  54. String s = sc.next();
  55. for (int i = 0; i < l; i++) {
  56. try {
  57. B.insert(s.charAt(i));
  58. } catch (Exception e) {
  59. e.printStackTrace();
  60. }
  61. }
  62. System.out.println("The length:"+A.length());
  63. A.display();
  64. System.out.println("The length:"+B.length());
  65. B.display();
  66. }
  67. }