题目描述
输入一个链表,输出该链表中倒数第k个结点。
代码实现
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
int count=0;
ListNode nn = head;
if(head == null)//空链表
return head;
while(nn!=null){//计算链表的长度
count++;
nn = nn.next;
}
if(count < k)//链表长度小于k
return null;
for(int i=0;i<count-k;i++){//定位到k结点的位置
head = head.next;
}
return head;
}
}