题目描述:面试题 02.02. 返回倒数第 k 个节点 - 力扣(LeetCode):
答案展示:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int kthToLast(struct ListNode* head, int k){
struct ListNode* fast,*slow;
fast = slow = head;
while(k--)
{
fast = fast->next;
}
while(fast)
{
fast = fast->next;
slow = slow->next;
}
return slow->val;
}
亮点:
使用了快慢指针,让快指针先走k补后同时走