思路: 1. 编写一个方法,接收head节点,同时接收一个index 2. index表示是倒数第index个节点 3. 先把链表从头到尾遍历,得到链表的总的长度getLength 4. 得到size后,我们从链表的第-一个开始遍历(size-index)个, 就可以得到倒数第k个节点 5. 如果找到了,则返回该节点,否则返回nulll
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode FindKthToTail(ListNode head,int k) { int i=getLenth(head); int j=i-k; ListNode cur=null; if(head==null||k>i||k<=0){ return null; } while(true){ if(j==0){ break; } head=head.next; j--; } return head; } /** * 获取单链表节点的有效个数 * @param head * @return */ public static int getLenth(ListNode head){ int length=0; if(head==null){ return 0; } ListNode cur=head; while (cur!=null){ length++; cur=cur.next; } return length; } }