package com.he.list;
import java.util.Arrays;
import org.w3c.dom.ls.LSException;
class ArrayList {
private int length;// the list's length
private int[] store;// store the data
// initialize an empty list
public ArrayList initList(String name) {
return new ArrayList();
}
public ArrayList() {
store = new int[0];
}
// get the list's length
public int getLength() {
return store.length;
}
// add data into the list
public void add(int data) {
if (store.length == 0) {
store = Arrays.copyOf(store, length + 1);
store[0] = data;
length++;
} else {
store = upSize();
store[store.length - 1] = data;
}
}
public boolean isEmpty() {
return length == 0;
}
public int[] upSize() {
store = Arrays.copyOf(store, ++length);
return store;
}
// index the list
public int get(int i) {
return store[i];
}
// find if the list contains data and return the index
public int contains(int data) {
for (int i = 0; i < length; i++)
if (store[i] == data)
return i;
return 0;
}
// delete a data in the list and the data's index is i
public boolean delete(int i) {
for (int t = i; t < length; t++) {
store[t - 1] = store[t];
}
store = Arrays.copyOf(store, length - 1);
return true;
}
}
public class MyArrayList {
public static void main(String[] args) {
ArrayList list = new ArrayList();
for (int i = 0; i <= 10; i++)
list.add(i);
for (int i = 0; i < list.getLength(); i++)
System.out.println(list.get(i));
System.out.println(list.isEmpty());
System.out.println(list.contains(1));
System.out.println(list.contains(10));
System.out.println(list.contains(111));
list.delete(9);
System.out.println(list.getLength());
for (int i = 0; i < list.getLength(); i++)
System.out.println(list.get(i));
}
}
数据结构线性表顺序结构的实现
最新推荐文章于 2022-10-24 19:41:13 发布