题目描述
输入一个链表,输出该链表中倒数第k个结点。
分析:
双指针法,让一个指针先走k补,当这个指针走到链表末尾的时候,那么当前指针就是倒数第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) {
ListNode step =head;
ListNode first =head;
if(k <=0)
return null;
for(int i=0;i<k;i++){
if(step != null){
step =step.next;
}else {
return null;
}
}
if(step ==null){
return head;
}
while(step.next != null){
step =step.next;
first =first.next;
}
//first.next.next =null;// =first.next.next;
return first.next;
}
}