链表不是数组,没办法直接查找第N个节点
需要自己开发一个方法来查找链表第N个节点
for循环查找数组 i=0 开始的
那么在求第n个节点,对于链表来说是没有 0 节点的
循环的伪代码 , n为第n个节点
- for(int i = 1 ; i
-
- }
假如求第一个节点,程序出现问题
3 dummyNode 节点概念引入
由于链表的特性,导致for循环的时候存在困难问题,所以不知哪位高人引入了 dummyNode
dummyNode为一个无用节点,作为原有链表的表头

这样的话,for循环的伪代码就完全使用与链表了
for(int i = 1 ; i
}
完整代码示例
- @Data
- public class ListNode {
-
- /**
- * 当前节点值
- */
- private int val;
-
- /**
- * 下一个节点
- */
- private ListNode next ;
-
-
- }
- public class ListNodeUtil {
-
-
- /**
- * 获取链表
- *
- * @return
- */
- public static ListNode getListNode(){
- ListNode one = new ListNode();
- one.setVal(1);
- ListNode two = new ListNode();
- two.setVal(2);
- ListNode three = new ListNode();
- three.setVal(3);
- ListNode four = new ListNode();
- four.setVal(4);
- ListNode five = new ListNode();
- five.setVal(5);
- one.setNext(two);
- two.setNext(three);
- three.setNext(four);
- four.setNext(five);
- return one;
- }
-
-
-
- }
- public static void main(String[] args) {
- ListNode listNode = ListNodeUtil.getListNode();
- ListNode dummyNode = new ListNode();
- dummyNode.setVal(0);
- dummyNode.setNext(listNode);
- int n = 1;
- for(int i = 0 ; i
- dummyNode = dummyNode.getNext();
- }
- System.out.println(dummyNode);
- }
-
相关阅读:
可恶,又是个线上问题!
21.3K star!推荐一款可视化自动化测试/爬虫/数据采集神器!功能免费且强大!
spark on yarn-cluster在生产环境 部署 spark 任务, 同时支持读取外部可配置化文件
祖冲之算法(ZUC算法)
VScode配置LuatOS开发模拟环境
SCI论文投稿格式准备(以光学类为例)与论文撰写模板-经验总结
【数据库】你听说过矢量数据库吗?
axios 和 fetch
Jmeter集成到jenkins
HarmonyOS应用开发者基础认证【满分答案】
-
原文地址:https://blog.csdn.net/an13654067079/article/details/126173743