141. linked list cycle#4
Conversation
lightbanana
commented
Jun 23, 2026
- 今回解いた問題: 141. Linked List Cycle(https://leetcode.com/problems/linked-list-cycle?envType=problem-list-v2&envId=xo2bgr0r)
- 次に解く問題: 20. Valid Parentheses(https://leetcode.com/problems/valid-parentheses?envType=problem-list-v2&envId=xo2bgr0r)
| def hasCycle(self, head: Optional[ListNode]) -> bool: | ||
| visited_node = set() | ||
| current_node = head | ||
| if head is None: |
There was a problem hiding this comment.
自分なら、コーナーケースで early return する場合、関数の一番上に書くと思います。理由は、関数宣言と early return の間に書かれた内容を、 early return のロジックを読む間、読み手が短期記憶に保持し続けなければならないためです。これは短期記憶の要領の無駄遣いになり、読み手にとって不要な認知負荷になると思います。
There was a problem hiding this comment.
ありがとうございます。納得しました。early returnの場合は関数の最初で書くように意識してみます。
| class Solution: | ||
| def hasCycle(self, head: Optional[ListNode]) -> bool: | ||
| visited_node = set() | ||
| current_node = head |
There was a problem hiding this comment.
current という単語に、あまり情報がないように思いました。単に node だけで十分だと思います。
current/previous/next と対比する場合には、付けても良いと思います。
There was a problem hiding this comment.
ありがとうございます!納得しました。形容詞を使う際は、対比するものがあるかどうかを意識して、対比先がなければ使わないようにしてみようと思います。
| return True | ||
| else: | ||
| visited.add(head) | ||
| head = head.next |
There was a problem hiding this comment.
こちらのコメントをご覧ください。
https://github.com/yukik8/leetcode/pull/6#discussion_r3287970237
There was a problem hiding this comment.
ありがとうございます。headが動くことに違和感があるという点に納得しました。連結リストを扱う際はheadは動かさず、別の変数に格納してから扱おうと思います。
| class Solution: | ||
| def hasCycle(self, head: Optional[ListNode]) -> bool: | ||
| visited = set() | ||
| while head: |
There was a problem hiding this comment.
こちらのコメントをご参照ください。
ksaito0629/leetcode_arai60#1 (comment)
There was a problem hiding this comment.
ありがとうございます。納得しました。boolの評価はis Noneなどの形で行うように意識します。