环形链表-找环点
leetcode: 141-环形链表
判断是否有环
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
struct ListNode* start = head;
struct ListNode* end = head;
while (end)
{
start = start->next;
if (end == NULL || (end = end->next) == NULL)
{
return false;
}
end = end->next;
if (start == end)
{
return true;
}
}
return false;
}
leetcode: 142-环形链表2
找第一个环点
方法一 :常用二指针找环的方法,两倍速,则相遇点到环入口的距离和链表头结点到链表环入口的距离相等。
struct ListNode * hasCycle(struct ListNode *head) {
if(head==NULL)
return false;
struct ListNode *slow=head;
struct ListNode *fast=head;
while(fast!=NULL&&fast->next!=NULL){
slow=slow->next;
fast=fast->next->next;
if(fast==slow)
return fast;
}
return NULL;
}
struct ListNode *detectCycle(struct ListNode *head){
struct ListNode * i=hasCycle(head);
if (i)
{
struct ListNode* q = head;
while (i != q) {
i = i->next;
q = q->next;
}
return q;
}
else return NULL;
}
方法二:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#define sl struct ListNode*
bool iscycle(struct ListNode* head)
{
sl step1 = head;
sl step2 = head;
while (step1)
{
step1 = step1->next;
if(step2 == NULL || (step2 = step2->next) == NULL )
{
return false;
}
step2 = step2->next;
if (step1 == step2)
{
return true;
}
}
return false;
}
struct ListNode *detectCycle(struct ListNode *head) {
if (head == NULL)
{
return NULL;
}
sl tmp = head;
sl pre = tmp;
bool isc = false;
isc = iscycle(head);
if (isc == false)
{
return NULL;
}
else
{
isc = false;
}
while (tmp)
{
pre = tmp;
tmp = tmp->next;
pre->next = NULL;
isc = iscycle(tmp);
pre->next = tmp;
if (isc != true)
{
return pre;
}
}
return NULL;
}