题目格式post
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { private int count = 0; private ListNode ret; public ListNode FindKthToTail(ListNode head,int k) { if(head == null) return null; FindKthToTail(head.next,k); count ++; if(count == k) ret = head; return ret; } }
解题思路一(比较懒的思路):this
经过递归往回推的时候经过一个计数器不断递增,若是计数器等于k,那么咱们就把这个节点保存下来。编码
源代码:spa
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { private int count = 0; private ListNode ret; public ListNode FindKthToTail(ListNode head,int k) { if(head == null) return null; FindKthToTail(head.next,k); count ++; if(count == k) ret = head; return ret; } }
这个代码并非很好,由于为了保存这个节点,我还额外建立了实例变量,这样的编码也只能用于作题。code
解题思路二(不使用递归):blog
好比说咱们一共有5个元素,要求倒数第2个元素,那么其实就是正向的求第4个元素,也就是(5-2+1)个元素,那么咱们的第一个元素就须要移动3次递归
可是对于链表咱们没法知道它一开始有几个元素,因此能够用另一种方法。it
咱们能够使用2个节点,咱们能够利用后一个节点的移动的次数来决定前一个元素移动的次数。io
仍是上面这个例子。一共有5个元素(但一开始咱们是不知道的),求倒数第2个元素class
源代码:
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode FindKthToTail(ListNode head,int k) { ListNode pre = head; ListNode post = head; if(head == null) return null; if(k <= 0) return null; //求出后一个节点该从第几个元素开始 for(int i = 0; i < k-1; i++) { post = post.next; if(post == null) return null; } while(post.next != null){ pre = pre.next; post = post.next; } return pre; } }