1.线性表
分类:顺序表,链表
特点:除了头结点和尾结点,每个元素都有前驱元素和后继元素。
线性表的实现:
package demo09recursion;
public class SequenceList<T> {
//存储元素的数组
private T[] list;
//数组大小
private int N;
//构造方法
public SequenceList(int capacity){
//初始化数组
this.list= (T[]) new Object[capacity];
this.N=0;
}
//将线性表置为空表
public void clear(){
this.N=0;
}
//判断当前线性表是否为空表
public boolean isEmpty(){
return N==0;
}
//获取线性表的长度
public int length(){
return N;
}
//获取指定位置的元素
public T get(int i){
return list[i];
}
//向线性表中添加元素t
public void insert(T t){
list[N++]=t;
}
//在i元素处插入元素t
public void insert(int i,T t){
//移动i元素后的索引
for(int index=N-1;index>i;index--){
list[index]=list[index-1];
}
//t添加到i索引处
list[i]=t;
}
//删除指定位置的元素,并返回该元素
public T remove(int i){
//记录索引i处的值
T current=list[i];
for(int index=N-1;index>i;index--){
list[index]=list[index+1];
}
N--;
return current;
}
//查找t元素第一次出现的位置
public int indexOf(T t){
for(int i=0;i<N;i++){
if(list[i].equals(t)){
return i;
}
}
return -1;
}
}
测试线性表:
package demo09recursion;
public class SequenceListTest {
public static void main(String[] args) {
SequenceList<String> nba = new SequenceList<>(10);
//测试添加
nba.insert("科比");
nba.insert("詹姆斯");
nba.insert("加内特");
nba.insert(1,"邓肯");
//测试获取
System.out.println("获取的第一个元素是:"+nba.get(1));
//测试删除
String rem = nba.remove(0);
System.out.println(rem);
//测试清空
nba.clear();
System.out.println(nba.length());
}
}
增加容量可变(resize)操作:
package demo09recursion;
public class SequenceList<T> {
//存储元素的数组
private T[] list;
//数组大小
private int N;
//构造方法
public SequenceList(int capacity){
//初始化数组
this.list= (T[]) new Object[capacity];
this.N=0;
}
//将线性表置为空表
public void clear(){
this.N=0;
}
//判断当前线性表是否为空表
public boolean isEmpty(){
return N==0;
}
//获取线性表的长度
public int length(){
return N;
}
//获取指定位置的元素
public T get(int i){
return list[i];
}
//向线性表中添加元素t
public void insert(T t){
//扩容
if(N==list.length){
resize(2*list.length);
}
list[N++]=t;
}
//在i元素处插入元素t
public void insert(int i,T t){
//扩容
if(N==list.length){
resize(2*list.length);
}
//移动i元素后的索引
for(int index=N-1;index>i;index--){
list[index]=list[index-1];
}
//t添加到i索引处
list[i]=t;
}
//删除指定位置的元素,并返回该元素
public T remove(int i){
//记录索引i处的值
T current=list[i];
for(int index=N-1;index>i;index--){
list[index]=list[index+1];
}
N--;
//缩容
if(N<list.length/2){
resize(list.length/4);
}
return current;
}
//查找t元素第一次出现的位置
public int indexOf(T t){
for(int i=0;i<N;i++){
if(list[i].equals(t)){
return i;
}
}
return -1;
}
//扩容和缩容
public void resize(int newsize){
//定义一个临时数组,指向原数组
T[] tmp=list;
//创建新数组
list=(T[])new Object[newsize];
//把原数组的数组拷贝到新数组即可
for (int i = 0; i < N; i++) {
list[i]=tmp[i];
}
}
}
顺序表的时间复杂度:
查找:O(1)
插入:O(n)
删除:O(n)
ArrayList的实现:
1.底层是否为数组
2.实现遍历iterator接口
3.容量可变操作