这个题是要求我们判断链表是否存在环,有则返回环开始的结点,没有则返回一个NULL;
废话就不说了,直入主题:
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode *detectCycle(struct ListNode *head) { struct ListNode* fast=head; struct ListNode* slow=head; while(fast&&fast->next) { slow=slow->next; fast=fast->next->next; if(fast==slow)//证明有环 { struct ListNode* meetNode=slow; while(meetNode!=head)//找入环的第一个结点 { meetNode=meetNode->next; head=head->next; } return head; } }//循环结束,证明无环 return NULL; }