LeetCode | 面试题 02.02. 返回倒数第 k 个节点
OJ链接
- 思路:定义两个快慢指针,让快指针先提前走k个节点,然后再让慢结点和快结点一起走,当快指针 == NULL时,慢指针就是倒数第k个节点
代码如下:
int kthToLast(struct ListNode* head, int k){struct ListNode* slow,*fast;slow = fast = head;while(k--){if(fast == NULL)return NULL;fast = fast->next;}while(fast != NULL){slow = slow->next;fast = fast->next;}return slow->val;
}