File tree Expand file tree Collapse file tree 2 files changed +66
-0
lines changed Expand file tree Collapse file tree 2 files changed +66
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ step3_floydにてwhileの条件にしていた`(fast && fast->next)`とその直後の`(!fast || !fast->next)`は反転しているだけで実質同じという指摘を受けて書き直す。
3
+ Pythonのようにwhileに対してelseをつけられないので、while(true)のループの中でif-elseで分岐させる。
4
+ while(true)の中で分岐させると、ネストが深くなってしまい個人的に避けている書き方だったが、こちらのほうがifが少なくできて読みやすい
5
+
6
+ */
7
+ class Solution {
8
+ public:
9
+ ListNode *detectCycle (ListNode *head) {
10
+ ListNode* slow = head;
11
+ ListNode* fast = head;
12
+
13
+ while (true ) {
14
+ if (fast && fast->next ) {
15
+ slow = slow->next ;
16
+ fast = fast->next ->next ;
17
+ if (slow == fast) {
18
+ break ;
19
+ }
20
+ } else {
21
+ return nullptr ;
22
+ }
23
+ }
24
+
25
+ ListNode* from_head = head;
26
+ while (slow != from_head) {
27
+ slow = slow->next ;
28
+ from_head = from_head->next ;
29
+ }
30
+ return from_head;
31
+ }
32
+ };
Original file line number Diff line number Diff line change
1
+ /*
2
+ https://discord.com/channels/1084280443945353267/1192728121644945439/1194203372115464272
3
+ を参考にstep4_floydを書き直した
4
+ >「機械の使い方の説明です。まず、青いランプが5つついていることを確認してください。ランプがついていなかった場合は、直ちに使用を中止して事務所に連絡してください。…長い使い方の説明…。」
5
+ >のほうが素直ですよね。
6
+ という説明がしっくりきた
7
+ 早期returnをしたほうが考えること減ってわかりやすくなる。
8
+ `while(fast && fast->next)`という書き方にこだわってしまっていたので、step4時点でこれが見えてなかった。
9
+ */
10
+ class Solution {
11
+ public:
12
+ ListNode *detectCycle (ListNode *head) {
13
+ ListNode* slow = head;
14
+ ListNode* fast = head;
15
+
16
+ while (true ) {
17
+ if (!fast || !fast->next ) {
18
+ return nullptr ;
19
+ }
20
+ slow = slow->next ;
21
+ fast = fast->next ->next ;
22
+ if (slow == fast) {
23
+ break ;
24
+ }
25
+ }
26
+
27
+ ListNode* from_head = head;
28
+ while (slow != from_head) {
29
+ slow = slow->next ;
30
+ from_head = from_head->next ;
31
+ }
32
+ return from_head;
33
+ }
34
+ };
You can’t perform that action at this time.
0 commit comments