思路:使用双指针,一个快指针,一个慢指针,快指针每次移动两个节点,慢指针每次移动一个节点,若为循环链表,则快慢指针必会相遇
/**
* 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* fast{ head };
ListNode* slow{ head };
if (head == NULL)
return false;
while (fast != NULL && fast->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
if (fast == slow)
return true;
}
return false;
}
};
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public bool HasCycle(ListNode head)
{
if(head == null)
return false;
ListNode i = head;
ListNode j = head;
while(j != null && j.next != null)
{
i = i.next;
j = j.next.next;
if(i == j)
{
return true;
}
}
return false;
}
}