leetcode算法题--链表中倒数第k个节点

原题链接:https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/

双指针

ListNode* getKthFromEnd(ListNode* head, int k) {
     
    ListNode *p = head, *q = head;
    while (q && k) {
     //q比p先走k步
        q = q->next;
        k--;
    }
    while (q) {
     //依次向后移
        p = p->next;
        q = q->next;
    }
    return p;
}

你可能感兴趣的:(算法)