Skip to content

Commit 7e31b82

Browse files
author
whd
committed
upload
1 parent ed8e760 commit 7e31b82

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

141 Linked List Cycle .cpp

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode(int x) : val(x), next(NULL) {}
7+
* };
8+
*/
9+
class Solution {
10+
public:
11+
bool hasCycle(ListNode *head) {
12+
ListNode *p = head, *q = head;
13+
auto next = [] (ListNode *x) {
14+
if (!x) {
15+
return x;
16+
}
17+
return x->next;
18+
};
19+
while (p && q) {
20+
p = next(p);
21+
q = next(q);
22+
q = next(q);
23+
if (p && q && p == q) {
24+
return true;
25+
}
26+
}
27+
return false;
28+
}
29+
};

0 commit comments

Comments
 (0)