【剑指Offer】链表中倒数第k个结点
题目描述
输入一个链表,输出该链表中倒数第k个结点。
快慢指针法,注意while循环条件是判断快指针的下一个结点是否为null
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(head == null || k <= 0) {
return null;
}
int i = 1;
ListNode slow = head;
ListNode fast = head;
for(i = 1; i < k; i++) {
if(fast.next != null) {
fast = fast.next;
}else{
break;
}
}
if(i != k) {
return null;
}
while(fast.next != null) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
}