Conversation
| tail = dummy_head | ||
| while stack: | ||
| node = stack[-1] | ||
| stack.pop() |
| ``` | ||
|
|
||
| inner functionのtype annotaionはpython3.10+のものとした。 | ||
| public APIとかではないのでつける必要はない気がした。 |
There was a problem hiding this comment.
拝見して、僕も気になったので調べてみました。
public APIsだと必須だけど、それ以外は必要に応じてって感じなんですね。。難しい
At least annotate your public APIs.
https://google.github.io/styleguide/pyguide.html#3191-general-rules
| - time complexity: O(n) | ||
| - space complexity: O(n) (auxiliary space: O(1)) | ||
|
|
||
| previousを返すのが少し気持ち悪い。nodeに注目していたのに、返すものがpreviousであることに不整合を感じる。 |
There was a problem hiding this comment.
仕事をループの途中で引き継いだとしましょう。
これが node と previous ね、という書き置きがあったら何言っているんだって感じじゃないですか。
先頭からひっくり返していって「まだひっくり返していない部分」と「もうひっくり返した部分」という引き継ぎになるでしょう。
node は、まだ一番注目しているくらいの意味でいいでしょうが、previous は、意味ではなくて操作の順番から付いている名前ですね。 意味と形式のどちらから名前を付けるかは状況次第で、なるべくパズルを作らないようにつけましょう。
| ```python | ||
| class Solution: | ||
| def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: | ||
| stack = [None] |
There was a problem hiding this comment.
自分はstackにNoneを入れるのが気になりました。反転した後の末尾のnextをNoneにするためだと思うのですが、その意図を汲むのが難しいように思います。素直に2つ目のwhileを抜けた後にNoneを代入するので良いかなと思いました。
| class Solution: | ||
| def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: | ||
| def reverse_list_helper( | ||
| head: ListNode | None, |
| return None, None | ||
| if head.next is None: | ||
| return head, head | ||
| reversed_head, reversed_tail = reverse_list_helper(head.next) |
There was a problem hiding this comment.
先に head.next を別の変数に入れて、head.next = None にしてから再帰したほうが、概念的には分かりやすい気がします。
There was a problem hiding this comment.
コメントありがとうございます。
reversed_tailにheadを取り付ける際に、head.next = Noneとするのも、reversed_tailを先に進めてからreversed_tail.next = Noneとするのも、少し違和感を感じていたので、この説明かなり腑に落ちました。
https://leetcode.com/problems/reverse-linked-list/description/