class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
int n = 0;
auto node = head;
while (node) {
node = node->next;
n ;
}
for (int i = 0; i < n; i ) {
if (i == n - k) return head;
head = head->next;
}
return nullptr;
}
};
2 双指针(中间隔k个点,同时前进)
代码语言:javascript复制
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
auto preK = head;
auto cur = head;
for (int i = 0; i < k; i )
cur = cur->next;
while (cur) {
cur = cur->next;
preK = preK->next;
}
return preK;
}
};