Find the starting point of the Loop of LinkedList | Linked List Cycle II
https://leetcode.com/problems/linked-list-cycle-ii/
soln 1:
use hash map hash nodes
if node appears which already is in hash table that is the first element with cycle
if all node are distinct then return null.
soln 2:
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head==NULL || head->next==NULL) return NULL;
ListNode *slow=head;
ListNode *fast=head;
ListNode *entry=head;
while(fast->next && fast->next->next){
slow=slow->next;
fast=fast->next->next;
if(slow==fast){
while(slow !=entry ){
slow=slow->next;
entry=entry->next;
}
return entry;
}
}
return NULL;
}
};
Comments
Post a Comment