package offer;
/**
* offer interview 15
*/
public class Test15 {
public static class ListNode{
int value;
ListNode next;
public ListNode(int value){
this.value = value;
this.next = null;
}
}
public static ListNode findKthToTail(ListNode head,int k){
if (k < 1 || head == null){
return null;
}
ListNode pointer = head;
for (int i = 1 ; i < k;i ++){
if (pointer.next != null){
pointer = pointer.next;
}else{
return null;
}
}
while (pointer.next != null){
head = head.next;
pointer = pointer.next;
}
return head;
}
public static void main(String[] args){
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
head.next.next.next.next.next = new ListNode(6);
head.next.next.next.next.next.next = new ListNode(7);
head.next.next.next.next.next.next.next = new ListNode(8);
head.next.next.next.next.next.next.next.next = new ListNode(9);
System.out.println(findKthToTail(head,1).value);
System.out.println(findKthToTail(head,5).value);
System.out.println(findKthToTail(head,9).value);
System.out.println(findKthToTail(head,10).value);
}
}