Article Directory
Method 1: Fast and slow pointers: time O(n), space O(1)
answer:
- Double pointer, one pointer moves k steps first, then the two pointers move backward at the same time, until the fast pointer is empty, return to the slow pointer
- k is greater than the summary points of the linked list: return to the head node, the fast pointer ran to empty
/**
* 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)
{
// 1.快慢指针:快指针先走k步,然后双指针同时向后走,直到快指针为空返回慢指针
if (head == nullptr)
return head;
ListNode* fast = head;
ListNode* slow = head;
while (k-- && fast)
{
fast = fast->next;
}
while (fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
};