题目描述


已知顺序表类的定义如下,实现各个成员函数。主函数中输入数据(以0结束)利用Insert函数依次将数据插入到表的1号位置,利用DispList按照逻辑次序输出表中元素,再输入一个要查找的元素,利用查找函数Locate查找其在表中的位置,最后利用Reverse函数将数据逆序,再利用DispList输出。
template
class SeqList{
public:
SeqList(); //构造函数,将表置空
~SeqList(){} //析构
int Locate(T x); //查找元素x在表中的位置,成功返回x在表中的位置,否则返回0
void Insert(int i, T x); //在表的i位置插入元素x
void Reverse(); //逆序表中数据
void DispList();
private:
T data[MaxSize]; //存储元素
int length; //顺序表实际长度
};

输入

输入样例说明:例如输入数据为:1 2 3 4 5 6 0 3,即将1,2,3,4,5,6插入表中的1号位置,得到逻辑次序为6,5,4,3,2,1的顺序表,3为在表中待查找的数据,3的位置为4。
输入:1 2 3 4 5 6 0 3
输出:
The length:6
The elements:
6 5 4 3 2 1
Found position:4
The length:6
The elements:
1 2 3 4 5 6
若查找的数据不存在,则输出:No found,例如下例
输入:1 2 3 4 5 6 0 9
输出:
The length:6
The elements:
6 5 4 3 2 1
No found
The length:6
The elements:
1 2 3 4 5 6

输出

样例输入

1 2 3 4 5 6 0 3

样例输出

The length:6
The elements:
6 5 4 3 2 1
Found position:4
The length:6
The elements:
1 2 3 4 5 6

提示

来源

Submit

  1. import java.util.Scanner;
  2. class SeqList{
  3. private Object[] listElem;
  4. private int length ;
  5. public SeqList(int maxSize) {
  6. length = 0;
  7. listElem = new Object[maxSize];
  8. }
  9. public Object get(int i) throws Exception {
  10. if(i<0||i>length -1)
  11. throw new Exception("No found");
  12. return listElem[i];
  13. }
  14. public void insert(int i, Object x) throws Exception {
  15. if (length == listElem.length)
  16. throw new Exception("full");
  17. if (i < 0 || i > length )
  18. throw new Exception("Invalid insertion position");
  19. for (int j = length ; j > i; j--)
  20. listElem[j] = listElem[j - 1];
  21. listElem[i] = x;
  22. length ++;
  23. }
  24. public void reverse() {
  25. for (int i = 0; i < length/2 ; i++) {
  26. Object temp = listElem[i];
  27. listElem[i] = listElem[length-i-1];
  28. listElem[length-i-1] = temp;
  29. }
  30. }
  31. public void display() {
  32. System.out.println("The length:"+length );
  33. System.out.println("The elements:");
  34. for (int j = 0; j < length ; j++) {
  35. System.out.print(listElem[j]+ " ");
  36. }
  37. System.out.println();
  38. }
  39. }
  40. public class Main {
  41. public static void main(String[] args) {
  42. SeqList L = new SeqList(10);
  43. Scanner sc = new Scanner(System.in);
  44. while(sc.hasNext()){
  45. int d = sc.nextInt();
  46. if(d==0)break;
  47. try {
  48. L.insert(0,d);
  49. } catch (Exception e) {
  50. e.printStackTrace();
  51. }
  52. }
  53. L.display();
  54. try {
  55. System.out.println("Found position:"+L.get(sc.nextInt()-1));
  56. } catch (Exception e) {
  57. System.out.println("No found");
  58. }
  59. L.reverse();
  60. L.display();
  61. }
  62. }