数据结构第二章:线性表的顺序表示和实现代码
1. 线性表的顺序表示和代码实现
package lineTable;
/**
* @author wcc
* @description 线性表的顺序表示和实现
*/
public class SequenceList<T> {
private int length;//元素
private final int defaultInitSize = 10;//元素
private T[] array;//数据对象,一系列T类型元素的集合,使用SequenceList<T>这种ADT抽象数据类型来进行操作
public SequenceList() {
length = 0;
array = (T[]) new Object[defaultInitSize];
}
public SequenceList(int size) {
this.length = 0;
this.array = (T[]) new Object[size];
}
//position为1添加为第一个元素,头元素,在指定位置处添加元素
public void add(T element, int position) {
//保证程序的健壮性
if (position < 1 || (position > (length + 1))) {
System.out.println("添加元素位置不合理");
System.exit(1);
}
//如果数组已经存满,需要进行扩容,默认扩容两倍
if (length == array.length) {
T[] newArr = (T[]) new Object[length * 2];
for (int i = 0; i < length; i++) {
newArr[i] = array[i];
}
array = newArr;
}
//插入在中间某个位置时,需要将此位置后的每一个元素向后移动一位,这里从最后一位开始向后移动一位,直到移动到position-1处
for (int i = length; i > position - 1; i--) {
array[i] = array[i - 1];
}
array[position - 1] = element;
length++;
}
//删除指定位置的元素,position为1,删除第一个元素,头元素
public void delete(int position) {
//首先进行position的校验
if (position < 1 || position > length) {
System.out.println("此位置不存在数据元素,不能删除");
System.exit(1);
}
//删除元素肯定不涉及扩容哈,比增加简单些,同时删除元素是该元素之后的所有元素向前移动一位,
// 从钙元素开始递增,这里并没有进行删除元素的保存返回,需要的话改下即可
for (int i = position - 1; i < length - 1; i++) {
array[i] = array[i + 1];
}
length--;
}
//在线性表中查找某个元素的位置
public int find(T obj) {
for (int i = 0; i < length; i++) {
if (array[i].equals(obj)) {
return i + 1;
}
}
return -1;//返回-1表示没有查询到此元素
}
//其它方法由于都简单一些就不写了先
public void show() {
for (int i = 0; i < length; i++) {
System.out.print(array[i] + ".");
}
}
public static void main(String[] args) {
SequenceList<Integer> t = new SequenceList<>();
t.add(1, 1);
t.add(2, 1);
t.add(3, 1);
t.add(4, 1);
t.add(5, 1);
t.add(6, 1);
t.add(7, 1);
t.add(8, 1);
t.add(9, 1);
t.add(10, 1);
t.add(11, 1);
t.add(12, 1);
t.show();
System.out.println();
t.delete(1);
t.show();
System.out.println("t.find(3) = " + t.find(3));
}
}
2.插入逻辑:
3.删除逻辑:
艾欧尼亚,昂扬不灭,为了更美好的明天而战(#^.^#)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构