线性表是一个线性结构的数据元素的集合,其中数据元素之间的关系是一对一的关系,即除了第一个和最后一个数据元素之外,其他元素都是有且只有一个前继元素和一个后继元素。
常用的线性结构有:线性表,栈,队列,一维数组。
二维数组、多维数组、广义表和树是属于非线性结构,非线性结构中各个元素数据不再保持在一个线性序列中,每个数据元素可能与零个或者多个其他数据元素发生联系。根据关系的不同,可以分为层次结构和群体结构。
线性表的简单数组实现
对线性表的所有操作我们都可以通过数组来实现,虽然数组是固定容量的,但是我们可以在需要的时候用双倍的容量来创建新的数组。
数组实现线性表MyArrayList:
API:
MyArryList() //创建初始容量的空表
int size()//获取表中元素数量
boolean isEmpty()//表是否为空
Item get(int index)//返回指定索引的元素
void set(int index,Item item)//将指定位置的元素设置指定的值
boolean add(Item item)//向表中添加一个元素
void remove(int index)//删除表中的指定元素
Iterator iterator()//获取迭代器
import java.util.Iterator;
import java.util.NoSuchElementException;
public class MyArryList<Item> implements Iterable<Item> {
private static final int DEFAULT_CAPACITY = 10; //初始容量
private int theSize;
private Item[] arry;
public MyArryList() {
arry = (Item[]) new Object[DEFAULT_CAPACITY];
}
public int size() {
return theSize;
}
public boolean isEmpty() {
return size() == 0;
}
public Item get(int index) {
//判断是否越界
if (index < 0 || index > size()) {
throw new ArrayIndexOutOfBoundsException();
}
return arry[index];
}
public void set(int index,Item item) {
if (index >= 0 && index <= size()) {
arry[index] = item;
}else {
throw new ArrayIndexOutOfBoundsException();
}
}
public boolean add(Item item) {
if (arry.length == size()) {
Item[] oldArry = arry;
arry = (Item[]) new Object[size()*2];
for (int i = 0;i < oldArry.length;i++) {
arry[i] = oldArry[i];
}
}
arry[size()] = item;
theSize++;
return true;
}
public void remove(int index) {
if(index >= 0 || index <= size()) {
for (int i = index;i < arry.length - 1;i++) {
arry[i] = arry[i+1];
}
theSize--;
}else {
throw new ArrayIndexOutOfBoundsException();
}
}
public Iterator<Item> iterator() {
return new ArrayListIterator();
}
private class ArrayListIterator implements Iterator<Item> {
private int current = 0;
public boolean hasNext() {
return current < size();
}
public Item next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return arry[current++];
}
}
}
测试用例:
import java.util.Iterator;
public class Test {
public static void main(String[] args) {
MyArryList<Integer> myArrayList = new MyArryList<Integer>();
myArrayList.add(0);
myArrayList.add(1);
myArrayList.add(3);
myArrayList.add(4);
myArrayList.add(5);
myArrayList.add(6);
myArrayList.add(7);
myArrayList.add(8);
myArrayList.add(9);
myArrayList.add(10);
myArrayList.add(11);
System.out.print("原始状态:");
for (Integer integer : myArrayList) {
System.out.print(integer + " ");
}
System.out.println();
System.out.println("获取元素个数:" + myArrayList.size());
System.out.println("获取指定元素:" + myArrayList.get(9));
myArrayList.set(0, 99);
myArrayList.remove(12);
System.out.print("迭代器测试:");
Iterator<Integer> it = myArrayList.iterator();
while(it.hasNext()) {
System.out.print(it.next() + " ");
}
}
}
运行结果:
利用数组来实现表,可以根据索引位置对元素进行快速随机访问,但是当需要删除特定位置的元素或者需要在特定位置插入元素的速度较慢,因为当删除特定位置的元素后,需要将该元素后面的所有元素都向前挪;在特定位置插入元素时,需要将该位置后面的所有元素都向后挪。