数组方式实现的线性表
class ArrayList{
private Object[] arr;
private int length;
public ArrayList(){
length = 20;
arr = new Object[20];
}
public ArrayList(int len){
length = len;
arr = new Object[len + 20];
}
public ArrayList(Object[] objs){
this.length = objs.length;
arr = objs;
}
public void append(Object obj){
if(arr.length > this.length){
arr[length] = obj;
}else{
Object[] temp = new Object[arr.length + 100];
for(int i = 0;i < length;i++){
temp[i] = arr[i];
}
temp[length] = obj;
arr = temp;
}
length++;
}
public void insert(int pos, Object obj){
try{
if(arr.length > this.length){
if(pos >= length){
throw new Exception("位置输入错误");
}else{
for(int i = this.length;i >= pos;i--){
arr[i] = arr[i - 1];
}
arr[pos] = obj;
}
}else{
if(pos >= length){
throw new Exception("位置输入错误");
}else{
Object[] temp = new Object[arr.length + 100];
for(int i = 0;i < length;i++){
temp[i] = arr[i];
}
arr = temp;
for(int i = this.length;i >= pos;i--){
arr[i] = arr[i - 1];
}
arr[pos] = obj;
}
}
this.length++;
}catch(Exception e){
e.printStackTrace();
}
}
public void delete(int index){
try{
if(index > this.length){
throw new Exception("输入位置有误");
}else{
for(int i = index;i < this.length - 1;i++){
arr[i] = arr[i + 1];
}
arr[length - 1] = null;
this.length--;
}
}catch(Exception e){
e.printStackTrace();
}
}
public void replace(int pos, Object obj){
try{
if(pos >= length){
throw new Exception("输入的位置有误");
}else{
arr[pos] = obj;
}
}catch(Exception e){
e.printStackTrace();
}
}
public boolean isEmpty(){
return length == 0?true:false;
}
public int getLength(){
return this.length;
}
public Object get(int index){
Object obj = null;
try{
if(index >= length){
throw new Exception("输入的位置有误");
}else{
obj = arr[index];
}
}catch(Exception e){
e.printStackTrace();
}
return obj;
}
public void printArr(){
System.out.print("{ ");
for(int i = 0;i < length;i++){
if(i == length - 1){
System.out.print(arr[i] + " }\n");
}else{
System.out.print(arr[i] + ",");
}
}
}
}