面试题22. 链表中倒数第k个节点

264 阅读1分钟

leetcode-cn.com/problems/li…

class Solution {
    public ListNode getKthFromEnd(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;
    }
}