83. Remove Duplicates from Sorted List - #3
Conversation
nanae772
left a comment
There was a problem hiding this comment.
お疲れ様です。私も昨日同じ問題に取り組んでいたので少しコメントさせていただきました。何か参考になれば幸いです。
|
|
||
| while node is not None and node.next is not None: | ||
| if node.val == node.next.val: | ||
| node.next = node.next.next |
There was a problem hiding this comment.
こちらのコードは元の連結リストを保持したまま重複を削除した新しい連結リストを作成する実装を目指したのだと認識しています。
nodeのほうは元の連結リストを指しているのでnode.next = node.next.nextと書いてしまうと既存の連結リストを変更してしまっているのではないでしょうか。
There was a problem hiding this comment.
nodeのほうは元の連結リストを指しているのでnode.next = node.next.nextと書いてしまうと既存の連結リストを変更してしまっているのではないでしょうか。
おっしゃる通りですね。元の連結リストを変更しない形で修正しました!
There was a problem hiding this comment.
ありがとうございます、非常にシンプルかつ分かりやすいコードでとても良いと思いました!
| added_node = ListNode(node.val) | ||
| new_node.next = added_node | ||
| new_node = added_node |
There was a problem hiding this comment.
added_nodeという変数を定義せずに単に以下のようにも書けるかなと思いました
| added_node = ListNode(node.val) | |
| new_node.next = added_node | |
| new_node = added_node | |
| new_node.next = ListNode(node.val) | |
| new_node = new_node.next |
There was a problem hiding this comment.
修正しました!提示頂いたやり方の方が、node = node.next と対比して書くことができるのでわかりやすいですね。
https://github.com/kazizi55/coding-challenges/pull/3/files#diff-153271ae97af52ab3609bb5e1cd3215deb7bc0ef64f6750b2220ed75868283f4R1-R14
| node.next = node.next.next | ||
| else: | ||
| node = node.next | ||
| return head |
| https://discord.com/channels/1084280443945353267/1228896007279083653/1231823840355815475 | ||
| https://discord.com/channels/1084280443945353267/1200089668901937312/1206180274442993694 | ||
|
|
||
| if node だと 0 や[]の時は true になるので、それらも false として判定してほしいときは if node is not None を使うのが良さそう。 |
There was a problem hiding this comment.
逆になっている気がします。None, 0, [] は False とみなされます。
https://docs.python.org/3/library/stdtypes.html#truth
https://google.github.io/styleguide/pyguide.html#214-truefalse-evaluations
There was a problem hiding this comment.
確かに逆に書いていました、、(引用元のコメントはあっていたので自分が逆に書いていただけです 😇 )
修正しました!
https://github.com/kazizi55/coding-challenges/pull/3/files#diff-f681381086b8efb4fb2a30f989bcdf016b07fa8c9207d1167321d3c62a58e6deR68-R71
|
|
||
| #### 個人的な好み | ||
|
|
||
| - 他の回答で、冒頭に if head is None と書いて早期 return しているものがあったが、その後で while node is not None と書くので、早期 return は冗長なのではと思った。新しい LinkedList を作る場合は head を使って new head を初期化する必要があるので必要ではある。 |
There was a problem hiding this comment.
早期 return でも結果が変わらない場合は消してもいいですね。読みやすさの助けになる場合には残すこともあるかもしれません。特に再帰とかです。
There was a problem hiding this comment.
ありがとうございます。
読みやすさの助けになる場合には残すこともあるかもしれません。特に再帰とかです。
確かに考え直してみて、後続の処理がとても長い時は、冗長でも早期 return で読まなくていい場合を明示した方が読みやすくなりますね。再帰の場合だとそれがより顕著なのかなと思います。
https://leetcode.com/problems/remove-duplicates-from-sorted-list/
Next: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii