题解 | #判断链表中是否有环#
判断链表中是否有环
https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
//快慢指针要以快指针作为判断条件
/**
* 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 == nullptr || head->next == nullptr) return false;
ListNode* first;
ListNode* second;
first = head;
second = head;
while (second->next && second->next->next) {
first = first->next;
second = second->next->next;
if (first == second)
return true;
}
return false;
}
};
传音控股公司福利 337人发布
