1、查找单链表中倒数第K个节点。head为链表头节点 index为倒数的位置
public static Node getNode(Node head,int index){ //得到链表的长度 int length = getLength(head); if (index<=0||index>length){ //不存在该节点 return null; } //定义辅助变量 用来接收下一个节点 Node node = head.next; //length-index为节点在链表中的位置 for (int i = 0; i < length-index; i++) { node = node.next; } return node; }
得到链表的长度,getLength()方法
public static int getLength(Node head){ if (head.next==null){ //空链表 return 0; } //定义辅助变量 统计有效节点的个数 int num = 0; Node node = head.next; while (node!=null){ num++; node = node.next; } return num; }
浙公网安备 33010602011771号