基于数组实现线性表(Java语言实现)
1.线性表的定义
线性表是由一组按照顺序排列的元素组成的数据结构,这些元素之间存在一对一的前后关系。
以数组a[n]为例,在Java中,首个索引 0 与之后的索引 1存在一对一的关系(后),最后一个索引n-1与最后倒数第二个索引之间存在关系(前)。(关系如下)
a
0
→
a
1
→
a
2
→
.
.
.
→
a
n
−
2
→
a
n
−
1
a_0 \rightarrow a_1 \rightarrow a_2 \rightarrow ... \rightarrow a_{n-2}\rightarrow a_{n-1}
a0→a1→a2→...→an−2→an−1
2.基本概念
元素:即数组里面存储的元素,比如 nums[0], nums[1];
索引:即数组的下标,比如0,1,2,3等;
大小:即元素存储个数的多少,比如在数组中存储了5个元素,大小即为5.
3.线性表的方法
//插入(在线性表后面增加一个新的元素)
public void addLast(int element)
//删除(根据索引删除元素)
public boolean remove(int index)
//修改(根据索引修改元素)
public boolean update(int index,int element)
//查询(根据索引查找元素)
public int get(int index)
//遍历
public void foreach(Consumer<Integer> consumer)
4.具体代码
public class ArrayList {
private int size = 0; //大小
private int capacity = 8; //数组容量,防止数组越界
private int[] array = {}; // 初始化数组
/**
* 向最后位置 [size] 添加元素
*
* @param element 待添加元素
*/
public void addLast(int element) {
add(size, element);
}
/**
* 向 [0 .. size] 位置添加元素
*
* @param index 索引位置
* @param element 待添加元素
*/
public void add(int index, int element) {
//容量检查
checkAndGrow();
// 添加逻辑
if (index >= 0 && index < size) {
// 向后挪动, 空出待插入位置
System.arraycopy(array, index,
array, index + 1, size - index);
}
array[index] = element;
size++;
}
// 容量检查
private void checkAndGrow() {
if (size == 0) {
array = new int[capacity];
} else if (size == capacity) {
// 进行扩容, 1.5 1.618 2
capacity += capacity >> 1;
int[] newArray = new int[capacity];
System.arraycopy(array, 0,
newArray, 0, size);
array = newArray;
}
}
/**
* 从 [0 .. size) 范围删除元素
*
* @param index 索引位置
* @return
*/
public boolean remove(int index) { // [0..size)
if(index < 0 || index > size){
return false;
}
int removed = array[index];
if (index < size - 1) {
// 向前挪动
System.arraycopy(array, index + 1,
array, index, size - index - 1);
}
size--;
return true;
}
/**
* 对索引index的元素修改为elemnt
* @param index 索引位置
* @param element 新的元素
* @return
*/
public boolean update(int index,int element){
if(index < 0 || index > size){
return false;
}
array[index] = element;
return true;
}
/**
* 查询元素
*
* @param index 索引位置, 在 [0..size) 区间内
* @return 该索引位置的元素
*/
public int get(int index) {
return array[index];
}
/**
* 遍历方法
*
*
*/
public void foreach() {
for (int i = 0; i < size; i++) {
// 提供 array[i]
System.out.print(array[i] + " ");
}
}
}
以上代码是通过学习网上视频并自己手动敲击,希望可以互相借鉴借鉴,如有不足之处,请在评论区多多指正!
如果还想深入了解,请私信我哦!(开始你的力扣之旅和牛客网吧)