[LeetCode]面试题 02.02. 返回倒数第 k 个节点

实现一种算法,找出单向链表中倒数第 k 个节点。返回该节点的值。

注意:本题相对原题稍作改动

示例:

输入: 1->2->3->4->5 和 k = 2
输出: 4
说明:

给定的 k 保证是有效的。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/kth-node-from-end-of-list-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int KthToLast(ListNode head, int k) {
        // 1
        // int len = 0;
        // ListNode test = head;
        // while(test != null){
        //     len++;
        //     test = test.next;
        // }

        // for(int i = 0; i < len-k; i++){
        //     head = head.next;
        // }

        // return head.val;

        // 2
        ListNode fast = head;
        ListNode slow = head;
        while(k > 0){
            fast = fast.next;
            k--;
        }

        while(fast != null){
            fast = fast.next;
            slow = slow.next;
        }

        return slow.val;
    }
}
原文地址:https://www.cnblogs.com/donpangpang/p/13571391.html