-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0141.LinkedListCycle.cpp
More file actions
39 lines (35 loc) · 954 Bytes
/
0141.LinkedListCycle.cpp
File metadata and controls
39 lines (35 loc) · 954 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*Question:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Subscribe to see which companies asked this question
Show Tags
Show Similar Problems
*/
/*思路:
两个指针pSlow和pFast同时走,在pSlow=pSlow->next, pFast=pFast->next->next(中间注意判断pFast是否为nullptr)
*/
//Code:
/**
* 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 *pSlow = head, *pFast = head;
while(pFast != nullptr && pFast->next != nullptr){
pSlow = pSlow->next;
pFast = pFast->next->next;
if(pFast == pSlow){
return true;
}
}
return false;
}
};