题目: 给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
题解思路: 方法一:双指针+快慢指针+判断是否相遇
函数代码:
class Solution { public: bool hasCycle(ListNode *head) { if(!head||!head->next) { return false; } ListNode *fast=head; ListNode *slow=head; while(fast->next&&fast->next->next) { fast=fast->next->next; slow=slow->next; if(slow==fast) { return true; } } return false; } };方法二:
函数代码:
class Solution { public: bool hasCycle(ListNode *head) { while(head) { if(head == head->next) { return true; } if(head->next) { head->next = head->next->next; } head = head->next; } return false; } };