题目描述:
输入一个链表,输出该链表中倒数第k个结点。
测试用例:
输入:1,{1,2,3,4,5}
输出:{5}
思路:
-判断参数的合法性;
-定义fast和slow节点分别指向头结点;
-当fast.next != null,fast先走k-1步;
-当fast.next != null,fast和slow一起走,最终返回slow;
代码如下:
class ListNode{
public int val;
public ListNode next;
public ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if (head == null || k <= 0){
return null;
}
ListNode fast = head;
ListNode slow = head;
for (int i = 0; i < k-1; i++) {
if (fast.next != null){
fast = fast.next;
}else {
return null;
}
}
while(fast.next != null){
fast = fast.next;
slow = slow.next;
}
return slow;
}
}