Skip to content

206 reverse linked list#7

Open
kitano-kazuki wants to merge 6 commits intomainfrom
206-reverse-linked-list
Open

206 reverse linked list#7
kitano-kazuki wants to merge 6 commits intomainfrom
206-reverse-linked-list

Conversation

@kitano-kazuki
Copy link
Owner

node.next = prev
prev = node
node = next_node
return prev
Copy link
Owner Author

@kitano-kazuki kitano-kazuki Feb 17, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

liruly/leetcode#9 (comment)

最後に返すオブジェクトが prev なのはあまり直感的ではないと感じました。

https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0#heading=h.x5w37bodndgj

仕事をループの途中で引き継いだとしましょう。
これが node と previous ね、という書き置きがあったら何言っているんだって感じじゃないですか。
先頭からひっくり返していって「まだひっくり返していない部分」と「もうひっくり返した部分」という引き継ぎになるでしょう。

* in-placeでも, 別のノードリストを用意してもできる.
* 再帰で実装もできるけど本質的にはやること一緒.

## Code1-1 (別のリストに数字を保存)
Copy link
Owner Author

@kitano-kazuki kitano-kazuki Feb 17, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

出題意図はstackではないにしろ, stackを使うという発想に至れば良かった

dxxsxsxkx/leetcode#7 (comment)

この問題の出題意図は、定数個のポインターを使って、参照先を繋ぎ変えていくというものだと思います。

[追記]
listの場合はreversedも選択肢に入れる
kazizi55/coding-challenges#7 (comment)

組み込み関数reversed()を使って、 for num in reversed(stack): と書くこともできます。どっちでもいいと思いますが、こちらのが自分は好みです。


## Code1-1 (別のリストに数字を保存)

* `values[::-1]`とするよりも, `range(len(values) - 1, -1, -1)`を使った方が, 配列が新たにコピーされなくて済むので効率的かと思ったが, 結局`range()`も新しく配列を新たに作成する上, 中に含まれるのはどちらも`int`型だから変わらない気がしてきた.
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

range は Python 3 から generator を作るので、効率的ではあります。reversed も generator ですので values[i] でしかアクセスしないならば、reversed(values) も手です。

速度の面ではコピーしてしまったほうが速い可能性はあります。
ひっくり返すのはネイティブコードなので1要素あたりナノ秒の桁くらいじゃないでしょうか。

いずれにしても、速さを問題にするならば、定量的に見積もって、本当に重要なのかを考えたいです。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

generatorを呼ぶ場合は初回にpythonframeを作るのでその分の時間がかかりそうですね。

今回は速さ的な意味だとそこまで気にする必要はない程度の差だと感じました。

一方で、リストが長くなる時はメモリの効率性の観点からgeneratorを返すものを使った方が良いと思いました。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants