目录
环形链表
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ bool hasCycle(struct ListNode *head) { struct ListNode*slow=head; struct ListNode*fast=head; while(fast&&fast->next)//同中间节点一样 { fast=fast->next->next; slow=slow->next; if(fast==slow) return true; } return false; }
.环形链表 2
* struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode *detectCycle(struct ListNode *head) { struct ListNode*slow=head; struct ListNode*fast=head; struct ListNode*mid=NULL; struct ListNode*init=head; while(fast&&fast->next) { fast=fast->next->next; slow=slow->next; if(fast==slow) { mid=fast;//mid在环里面,而init在环外面,相遇的节点就是进入的节点 while(mid!=init) { mid=mid->next; init=init->next; } return mid; } } return NULL; }