# 剑指offer第二版-22.链表中倒数第k个节点

chapter3主要考察细节，这道题也不例外。需要注意链表是否为空，链表长度是否达到k，k是否是个正数。

``````package structure;
/**
* Created by ryder on 2017/6/13.
*/
public class ListNode<T> {
public T val;
public ListNode<T> next;
public ListNode(T val){
this.val = val;
this.next = null;
}
@Override
public String toString() {
StringBuilder ret = new StringBuilder();
ret.append("[");
for(ListNode cur = this;;cur=cur.next){
if(cur==null){
ret.deleteCharAt(ret.lastIndexOf(" "));
ret.deleteCharAt(ret.lastIndexOf(","));
break;
}
ret.append(cur.val);
ret.append(", ");
}
ret.append("]");
return ret.toString();
}
}
``````
``````package chapter3;
import structure.ListNode;
/**
* Created by ryder on 2017/7/14.
* 链表中倒数第k个节点
*/
public class P134_KthNodeFromEnd {
public static ListNode<Integer> findKthToTail(ListNode<Integer> head,int k){
return null;
for(int i=0;i<k;i++){
//i==k-1,第三个测试例通不过
if(fast.next!=null || i==k-1)
fast = fast.next;
else
return null;
}
while(fast!=null){
slow = slow.next;
fast = fast.next;
}
return slow;
}
public static void main(String[] args){
``````3