Monday, February 21, 2022

Leetcode 141. Linked List Cycle

141. Linked List Cycle Point: - Two Pointer Technique for Linked List
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
// Two pointer technique
bool hasCycle(ListNode *head) {
if(!head) return false;
auto slow = head;
auto fast = head;
while(slow->next and fast->next and fast->next->next){
slow = slow->next;
fast = fast->next->next;
if(slow == fast) return true;
}
return false;
}
};

No comments:

Post a Comment