JZ14 链表中倒数最后k个结点
本文最后更新于:2022年4月9日 中午
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
class Solution { public:
ListNode* FindKthToTail(ListNode* pHead, int k) { if (!pHead || k <= 0) return nullptr; ListNode* dummyHead = new ListNode(-1); dummyHead->next = pHead; ListNode* slow = dummyHead, *fast = dummyHead; while (k--) { if (fast) { fast = fast->next; } } while (fast) { slow = slow->next; fast = fast->next; } return slow == dummyHead ? nullptr : slow; } };
|