public class P134_KthNodeFromEnd {
static class ListNode<T> {
T val;
ListNode<T> next;
ListNode(T val) {
this.val = val;
this.next = null;
}
@SuppressWarnings("all")
@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();
}
}
private static ListNode findKthToTail(ListNode head, int k) {
if (head == null || k < 1) {
return null;
}
ListNode node = head;
for (int i = 0; i<k - 1;i++){
if (node.next != null){
node = node.next;
}
else {
return null;
}
}
while (node.next !=null){
head = head.next;
node = node.next;
}
return head;
}
public static void main(String[] args) {
ListNode<Integer> head = new ListNode<>(1);
head.next= new ListNode<>(2);
head.next.next = new ListNode<>(3);
System.out.println(findKthToTail(head,1).val);
System.out.println(findKthToTail(head,2).val);
System.out.println(findKthToTail(head,3).val);
System.out.println(findKthToTail(head,4));
}
}