﻿ (LeetCode OJ) 141. Linked List Cycle-C 语言_软件编程-脚本宝典

# (LeetCode OJ) 141. Linked List Cycle

## (LeetCode OJ) 141. Linked List Cycle

141 Linked List CycleMy SubmissionsQuestionTotal Accepted: 88665 Total Submissions: 241622 Difficulty: MediumGiven a linked list, determine if it has a cycle

Question

Total Accepted: 88665 Total
Submissions: 241622 Difficulty: Medium

Given a linked list, determine if it has a cycle in it.

Can you solve it without using extra space?

to see which companies asked this question

Hide Tags
Two
Pointers

Hide Similar Problems

```/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
//思路首先：如果有环？遍历链表将无法走完，如果无环终会走到尾为NULL的位置
//让一个指针每次走一个，一个指针每次走两个位置，如果其中一个为NULL则无环，如果相遇了
//则有环
class Solution {
public:
return false;
while(true)
{
if(showNode->next!=NULL)
showNode=showNode->next;
else
return false;
if(fastNode->next!=NULL && fastNode->next->next!=NULL)
fastNode=fastNode->next->next;
else
return false;
if(showNode==fastNode)
return true;
}
return false;
}
};```
Tags：

﻿
<