问题:
输入一个链表,输出该链表中倒数第k个结点。
实例:
原题OJ链接
https://editor.csdn.net/md?not_checkout=1&spm=1000.2115.3001.4503&articleId=130832119
解答
/*
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 slow = head;
ListNode fast = head;
while (fast != null && fast.next != null ) {
while (k > 1) {
fast = fast.next;
k--;
}
fast = fast.next;
slow = slow.next;
}
return slow;
}
}