其他分享
首页 > 其他分享> > 【剑指Offer 22】链表中倒数第k个节点

【剑指Offer 22】链表中倒数第k个节点

作者:互联网

/**
 * 剑指 Offer 22. 链表中倒数第k个节点
 * https://leetcode.cn/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/
 * 
 * 思路:快慢指针
 * */
public class Solution {
    public ListNode getKthFromEnd(ListNode head, int k) {
        ListNode prev = head;
        ListNode next = head;
        // next 指针先走 k 步
        for (int i = 0; i < k; i++) {
            next = next.next;
        }
        // prev, next 同时移动
        while (next != null) {
            prev = prev.next;
            next = next.next;
        }
        return prev;
    }
}

标签:head,ListNode,22,int,next,链表,prev,倒数第
来源: https://www.cnblogs.com/liaozibo/p/offer-22.html