File tree Expand file tree Collapse file tree 3 files changed +70
-0
lines changed Expand file tree Collapse file tree 3 files changed +70
-0
lines changed Original file line number Diff line number Diff line change
1
+ // 早いのと遅いので競争をするというネタを知っていたので、それをそのまま実装。
2
+ class Solution {
3
+ public:
4
+ bool hasCycle (ListNode *head) {
5
+ ListNode* fast = head;
6
+ ListNode* slow = head;
7
+
8
+ while (fast && slow) {
9
+ fast = fast->next ;
10
+ if (!fast) {
11
+ return false ;
12
+ }
13
+ fast = fast->next ;
14
+
15
+ slow = slow->next ;
16
+
17
+ if (slow == fast) {
18
+ return true ;
19
+ }
20
+ }
21
+
22
+ return false ;
23
+ }
24
+ };
Original file line number Diff line number Diff line change
1
+ // whileの中をなるべくシンプルにするため、fast returnやfastの初期化部分を修正
2
+ // while中のfastの状態チェックをwhileの継続条件に取り込む
3
+ class Solution {
4
+ public:
5
+ bool hasCycle (ListNode *head) {
6
+ if (!head) {
7
+ return false ;
8
+ }
9
+
10
+ ListNode* fast = head->next ;
11
+ ListNode* slow = head;
12
+
13
+ while (fast && fast->next ) {
14
+ if (slow == fast) {
15
+ return true ;
16
+ }
17
+
18
+ fast = fast->next ->next ;
19
+ slow = slow->next ;
20
+ }
21
+
22
+ return false ;
23
+ }
24
+ };
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ bool hasCycle (ListNode *head) {
4
+ if (!head) {
5
+ return false ;
6
+ }
7
+
8
+ auto fast = head->next ;
9
+ auto slow = head;
10
+
11
+ while (fast && fast->next ) {
12
+ if (fast == slow) {
13
+ return true ;
14
+ }
15
+
16
+ fast = fast->next ->next ;
17
+ slow = slow->next ;
18
+ }
19
+
20
+ return false ;
21
+ }
22
+ };
You can’t perform that action at this time.
0 commit comments