剑指offer57

476 阅读1分钟

题目描述

输入一个链表,输出该链表中倒数第k个结点。

解题思路分析

这个题目很经典,我们只要先让一个节点从头先走k- 1步,然后另一个从头开始走,先走的到达了结尾之后,后面那个就到了倒数第K个节点了

代码实现

public ListNode findKthNode(ListNode head, int k) {
    if (head == null || k <= 0) {
        return null;
    }
    ListNode pAhead = head;
    for (int i = 0; i < k - 1; i++) {
        if (pAhead.next != null) {
            pAhead = pAhead.next;
        } else {
            return null;
        }
    }
    ListNode pBehind = head;
    while (pAhead.next != null) {
        pAhead = pAhead.next;
        pBehind = pBehind.next;
    }
    reutrn pBehind;
}