链表中倒数第K个节点,递归,Java
链表中倒数第k个结点
http://www.nowcoder.com/questionTerminal/529d3ae5a407492994ad2a246518148a
递归返回时需要记录一下返回到倒数第几个节点了
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { int n = 0; int i = -1; public ListNode FindKthToTail(ListNode head,int k) { i ++; if(head == null) { return null; } head.next = FindKthToTail(head.next, k); n ++; if(i < k) { return null; } // 这里是把倒数第K个节点当做头结点返回了 return n <= k ? head : head.next; } }