LeetCode 面试题02.02

297 阅读1分钟

leetcode-cn.com/problems/kt…

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

        int index = 0;
        while (index < length - k) {
            headParm = headParm.next;
            index ++;
        }
        return headParm.val;
    }
}