141. Linked List Cycle
Easy
1969284FavoriteShare
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:
Input: head = [1,2], pos = 0 Output: true Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:
Input: head = [1], pos = -1 Output: false Explanation: There is no cycle in the linked list.

Follow up:
Can you solve it using O(1) (i.e. constant) memory?
Accepted
493,678
Submissions
1,271,790
/**
* 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;
int cnt=0;int flag=0;
while(head->next!=NULL){
head=head->next;
cnt++;
if(cnt>10000){//循环大于10000的话肯定有环
flag=1;break;
}
}
return flag;
}
};
本文探讨了如何判断链表中是否存在循环。通过一个简单的算法,我们可以在一定条件下有效地检测到链表中的循环。文章提供了三个示例,展示了不同情况下链表循环的检测结果。
806

被折叠的 条评论
为什么被折叠?



