Skip to content

Commit 3d4a0c6

Browse files
committed
Add codes
1 parent 21f51a9 commit 3d4a0c6

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed

141/step1.cpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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+
};

141/step2.cpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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+
};

141/step3.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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+
};

0 commit comments

Comments
 (0)