NowCoder | 链表中倒数第k个结点
OJ链接
- 思路:定义两个快慢指针,让快指针先提前走k个节点,然后再让慢结点和快结点一起走,当快指针 == NULL时,慢指针就是倒数第k个节点
代码如下:
struct ListNode* FindKthToTail(struct ListNode* pListHead, int k ) {// write code herestruct ListNode* slow = pListHead;struct ListNode* fast = pListHead;while(k--){if(fast == NULL)return NULL;fast = fast->next;}while(fast){fast = fast->next;slow = slow->next;}return slow;
}