今天来说说线性表的实现
这里以List作为例子
~~~
package com.ray.testobject;
public class List {
private int length;
private Man[] array;
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public Man[] getArray() {
return array;
}
public void setArray(Man[] array) {
this.array = array;
}
}
~~~
list只是简单的封装了一个数组和一个整形数的长度
~~~
package com.ray.testobject;
public class Test {
// 构造一个不满的线性表出来
private List initList() {
List list = new List();
int n = 5;
list.setArray(new Man[n + 1]);// 构造多一个元素的线性表
for (int i = 0; i < n; i++) {
Man man = new Man();
man.setId(i);
list.getArray()[i] = man;
list.setLength(i + 1);
}
return list;
}
private boolean insertElement(List list, int pos, Man e) {
boolean flag = false;
Man[] array = list.getArray();
if (list.getLength() == array.length) {
return false;
}
if (pos < 1 || pos > array.length) {
return false;
}
if (pos < array.length) {
for (int i = array.length-1; i > pos-1; i--) {
array[i] = array[i - 1];
}
}
array[pos] = e;
list.setLength(list.getLength() + 1);
return flag;
}
public static void main(String[] args) {
Test test = new Test();
List list = test.initList();
Man man = new Man();
man.setId(10);
test.insertElement(list, 3, man);
for (int i = 0; i < list.getArray().length; i++) {
System.out.println(list.getArray()[i].getId());
}
}
}
~~~
在上面的测试类里面,我们实现了List的初始化与插入元素,后面还会继续实现删除等方法