//获取链表长度 public int getLength(HeroNode head){ if(head.next == null) return 0; //leangth: 长度 //cur:辅助变量,帮助遍历,未统计头节点 int length = 0; HeroNode cur = head.next; while(cur != null){ length++; cur = cur.next; } return length; }
//1、接受头节点 head,和目标节点 index(即倒数的节点) //2、遍历整个单链表,得到链表的总长度 size //3、得到 size 后 从链表第一个开始遍历(size-index)个,就可找到目标节点 //4、若找到,则返回该节点,否则返回 null public HeroNode findLastIndexNode(HeroNode head, int index){ if(head.next == null) return null; int size = getLength(head); //超出范围,则返回 null if(index <= 0 || index > size) return null; //第二次遍历,到达 size-index 即到达倒数第 K 个节点 HeroNode cur = head.next; for (int i = 0; i < size - index; i++) { cur = cur.next; } return cur; }
实现比较简单,使用的是全部遍历的笨办法