题目描述
遍历一次,且不用额外空间。
C++ 代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* findKthToTail(ListNode* head, int k) {
ListNode *first = head, *second = head;
while(k -- && first) {//直接走到不能走。
first = first->next;
}
if (k >= 0) return NULL;//如果k>=0,说明k比链表长。直接返回NULL。
else {
while(first) {
first = first->next;
second = second->next;
}
return second;
}
}
};