Skip to content

Commit e9a8832

Browse files
authored
【141. Linked List Cycle】【C++】
【141. Linked List Cycle】【C++】
2 parents 6935b73 + 72a6b4e commit e9a8832

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

算法思维系列/双指针技巧.md

+22
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,28 @@ void reverse(int[] nums) {
237237

238238
======其他语言代码======
239239

240+
[deardeer7](https://github.com/DearDeer7/) 提供 C++ 代码
241+
```cpp
242+
class Solution {
243+
public:
244+
bool hasCycle(ListNode *head) {
245+
// 链表为空或有一个元素,则无环
246+
if(!head || !head->next) return false;
247+
248+
ListNode* slow = head;
249+
ListNode* fast = head->next;
250+
251+
while(fast && fast->next) {
252+
fast = fast->next->next;
253+
slow = slow->next;
254+
// 快慢指针相遇,则有环
255+
if(fast == slow) return true;
256+
}
257+
return false; // 链表走完,快慢指针未相遇,则无环
258+
}
259+
};
260+
```
261+
240262
[ryandeng32](https://github.com/ryandeng32/) 提供 Python 代码
241263
```python
242264
class Solution:

0 commit comments

Comments
 (0)