链表反转及查找倒数第K个节点数据
/** * 实现链表的反转 * @param head 链表的头节点 */ public static void reverseList(HeroNode head){ // 如果链表为空或者只有一个节点,则直接返回即可,无需进行反转 if(head.next == null || head.next.next == null){ return; } // 实现链表的反转 HeroNode temp = head.next; HeroNode tm = null; //周转 HeroNode heroNode1 = new HeroNode(); while(temp != null){ tm = temp.next; temp.next = heroNode1.next; heroNode1.next = temp; temp = tm; } head.next = heroNode1.next; } /** * 查找倒数第K个节点的下标,并且展示数据 * @param head 链表的头节点 * @param index 倒数的第K个节点下标 * @return 返回第K个节点数据 */ public static HeroNode getHeroNode(HeroNode head,int index){ if (head.next == null){ System.out.println("链表为空"); return null; } if(index > getNum(head)||index <= 0){ System.out.println("您查询的数据不存在"); return null; } // 获得有效的节点个数 int size = getNum(head); int no = size - index + 1; HeroNode temp = head.next; int length = 0; while(temp != null){ length++; if (length == no){ break; } temp = temp.next; } return temp; } /** * 静态方法 * @return 获取节点的个数 */ public static int getNum(HeroNode head){ if (head.next == null){ // 表示没有节点 return 0; } HeroNode temp = head.next; int length = 0; while (temp != null){ length++; temp = temp.next; } return length; } }