题目
给你一个链表的头节点 head ,判断链表中是否有环。
思路
快慢指针。开始快指针在慢指针前面,当快指针等于慢指针时说明有环,如果快指针指向null时说明无环。
代码
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/
class Solution {
public:bool hasCycle(ListNode *head) {ListNode *first =head,*second=head;while(first&&second){first=first->next;if(first==NULL){break;}if(first==second){return true;}first =first->next;second = second->next;if(first&&second&&first==second){return true;}}return false;}
};