Java - 单链表
链表是一种常见的基础数据结构,是一种有序的列表,但不会按照线性顺序存储数据,而是在每一个节点里存储下一个节点的指针(next)。链表适合插入、删除,不宜过长,否则会导致遍历性能下降。
- 以节点方式存储;
- 每个节点包含data域,next域:指向下一个节点;
- 链表的各个节点不一定是连续存储的;
代码实现:
节点类
public class HeroNode { protected Integer no; protected String name; protected HeroNode next; public HeroNode(Integer no, String name) { this.no = no; this.name = name; } @Override public String toString() { return "HeroNode[" + "no=" + no + ", name='" + name + '\'' + ']'; } }
SingleLinkedList

public class SingleLinkedList { private HeroNode root; private Integer size = 0; /** * 添加至链表头 * @param hero */ public void addFirst(HeroNode hero) { if (root == null) { root = hero; } else { hero.next = root; root = hero; } size++; } /** * 添加至链表尾 * @param hero */ public void addLast(HeroNode hero) { if (root == null) { root = hero; } else { HeroNode temp = root; while (temp.next != null) { temp = temp.next; } temp.next = hero; } size++; } /** * 按照某属性的顺序添加 * @param hero */ public void addByOrder(HeroNode hero) { if (root == null) { root = hero; } else { HeroNode tmp = root; // 新节点比头节点小 if (hero.no < tmp.no) { root = hero; root.next = tmp; return; } // 找到next节点编号大于等于新节点的编号的节点,该节点与它的next节点之间就是新节点所在位置, // 等于时不添加,控制台进行提示 while (tmp.next != null && tmp.next.no < hero.no) { tmp = tmp.next; } if (tmp.next == null) { tmp.next = hero; return; } if (tmp.next.no.equals(hero.no)) { System.out.println("编号为" + hero.no + "已存在"); return; } hero.next = tmp.next; tmp.next = hero; } size++; } /** * 修改 * @param hero */ public void modify(HeroNode hero) { HeroNode tmp = root; while(tmp !=null) { if (tmp.no.equals(hero.no)) { tmp.name = hero.name; break; } tmp = tmp.next; } } /** * 根据编号获取节点 * @param no * @return */ public HeroNode query(int no) { HeroNode tmp = root; while (tmp != null) { if (tmp.no.equals(no)) { return tmp; } tmp = tmp.next; } return null; } /** * 根据编号删除节点 * @param no */ public void remove(int no) { if (root == null) { return; } //根节点 if (no == root.no) { if (null != root.next) { root = root.next; } else { root = null; } size--; return; } // 非根节点 HeroNode temp = root; while (temp.next != null) { if (no == temp.next.no) { break; } temp = temp.next; } // 节点不存在 if (temp.next == null) { return; } temp.next = temp.next.next; size--; } /** * 打印 */ public void display() { if (root == null) { System.out.println("This SingleLinkedList is null."); return; } HeroNode temp = root; while(temp != null) { System.out.println(temp.toString()); temp = temp.next; } } /** * 获取链表长度 * @return */ public Integer getSize() { return size; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?