First, the subject description:
Input a linked list, the linked list output reciprocal k-th node.
Second, the problem-solving ideas:
1, the length of chain required size.
2, the k-node is equal to the reciprocal of the number of positive (size-k) nodes.
3, over the interest list, go (size-k) step can be.
Third, Code Description:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
//判断k的合法性
if(k<0||k>size){
return null;
}
int size=getSize(head);
int steps=size-k;
ListNode cur=head;
for(int i=0;i<steps;i++){
cur=cur.next;
}
return cur;
}
//获取链表长度
private int getSize(ListNode head){
int size=0;
for(ListNode cur=head;cur!=null;cur=cur.next){
size++;
}
return size;
}
}