题目描述
已知一个有序顺序表类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
//主函数
int main(){
SortList
//生成一个有序表A
CreateSort(A);
SortList
CreateSort(B);
A.DispList();
B.DispList();
return 0;
}
//构造有序表A:函数定义
template
void CreateSort(SortList
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
提示
来源
提交
import java.util.Scanner;class SqList {private Object[] listElem;private int curLen;private String type;public SqList(int maxSize,String type) {curLen = 0;listElem = new Object[maxSize];this.type = type;}public int length() {return curLen;}public void insert(Object x) throws Exception {if (curLen == listElem.length)throw new Exception("顺序表已满");int i;for(i = 0;i<curLen;i++){if(type.equals("int")){if((int)listElem[i]>(int)x)break;}else{if((char)listElem[i]>(char)x)break;}}for (int j = curLen; j > i; j--)listElem[j] = listElem[j - 1];listElem[i] = x; // 插入 xcurLen++; // 表长加1}public void display() {System.out.println("The elements:");for (int j = 0; j < curLen; j++) {System.out.print(listElem[j]+ " ");}System.out.println();}}public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);SqList A ;int l = sc.nextInt();A = new SqList(l,"int");for (int i = 0; i < l; i++) {try {A.insert(sc.nextInt());} catch (Exception e) {e.printStackTrace();}}SqList B;l = sc.nextInt();B = new SqList(l,"char");String s = sc.next();for (int i = 0; i < l; i++) {try {B.insert(s.charAt(i));} catch (Exception e) {e.printStackTrace();}}System.out.println("The length:"+A.length());A.display();System.out.println("The length:"+B.length());B.display();}}
