若链表中有环,则设置两个指针均从头结点开始行进,快指针一次走两步,慢指针一次走一步,若有环,则快慢指针总会相遇,返回true,否则返回 false
代码如下:
/** * 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) { if(head == NULL) return false; ListNode *fast = head; ListNode *slow = head; while(fast->next != NULL && fast->next->next != NULL) { fast = fast->next->next; slow = slow->next; if(fast == slow) return true; } return false; } };
全部评论
(0) 回帖