题解 | #链表中倒数第k个结点#
链表中倒数第k个结点
https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * * @param pListHead ListNode类 * @param k int整型 * @return ListNode类 */ struct ListNode* FindKthToTail(struct ListNode* pListHead, int k ) { //思路2:快慢指针,快指针先走k步,然后快慢指针一起走,当快指针等于NULL时,慢指针的位置就是要找的 //快指针先走k步,然后快慢一起走,这样一直保持着k个距离,当快指针到最后时,慢指针就是倒数第k个 struct ListNode* slow = pListHead; struct ListNode* fast = pListHead; k = k - 1; while (k--) { if (fast == NULL) return NULL; fast = fast->next; if (fast == NULL) return NULL; } while (fast->next) { slow = slow->next; fast = fast->next; } return slow; }