Tortoise & Hare Algorithm
The Tortoise and the Hare algorithm implies we have 2 pointers which have these properties:
Pointer1 is faster than pointer2 (the hare)
Pointer2 is slower than pointer1 (the tortoise)
This algorithm can be implemented as a linked list like so:
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode* fast = head;
ListNode* slow = fast;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
};Or as a regular list like so:
Although this doesn't hit all nodes in the list, it can be useful to have a pointer trailing behind our hare pointer.
Last updated
Was this helpful?