Tuesday, February 22, 2022

Template: Two-Pointer in Linked List

// Initialize slow & fast pointers
ListNode* slow = head;
ListNode* fast = head;
/**
* Change this condition to fit specific problem.
* Attention: remember to avoid null-pointer error
**/
while (slow && fast && fast->next) {
slow = slow->next; // move slow pointer one step each time
fast = fast->next->next; // move fast pointer two steps each time
if (slow == fast) { // change this condition to fit specific problem
return true;
}
}
return false; // change return value to fit specific problem
References - https://leetcode.com/explore/learn/card/linked-list/214/two-pointer-technique/1216/ Problems - LeetCode

No comments:

Post a Comment