链表中倒数第k个节点

Description

image-20210904131800934

Solution

Using fast-slow pointers, let fast pointer firstly walk k step then slow and fast walk togerther.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
ListNode *fast = head, *slow = head;
for(int i = 0; i < k; i++)
fast = fast->next;
while(fast != nullptr){
fast = fast->next;
slow = slow->next;
}
return slow;
}
};