/** * 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个 if (pListHead == NULL) return NULL; struct ListNode* slow = pListHead; struct ListNode* fast = pListHead; k = k - 1; while (k--) { fast = fast->next; if (fast == NULL) return NULL; } while (fast->next) { slow = slow->next; fast = fast->next; } return slow; }