Conversation
| if (head == null || head.next == null) { | ||
| return head; | ||
| } |
| 他の解法も考えみる。 | ||
|
|
||
| - https://github.com/shintaroyoshida20/leetcode/pull/12/files#diff-62f050819b0cae018db7450bb0f0341942d799ece31ce3d0d1d4a64d45578363R24 | ||
| - 再帰で解く方法があるようなのでチャレンジしたい |
There was a problem hiding this comment.
はい、Approach 5の方でトライしてみました。
| 空間計算量: O(1) | ||
|
|
||
| - リンクを順番にひっくり返していく方法 | ||
| - 単に next だと再接続前か後かがわかりづらかったので、old とつけた。この命名がレビュアーにどう思われるかは気になるところ |
There was a problem hiding this comment.
oldNext が node.next ということは、新しい接続先(newNext)が prev ということでしょうか。「リンクに注目する」という意味を捉えられているかわかりませんが、自分としては nextNode などでも違和感ないかもしれないです。
There was a problem hiding this comment.
oldNextを使うのであればprevをnewNextとしたほうが読みやすいかもしれないです。
There was a problem hiding this comment.
ありがとうございます。いずれも参考にさせていただきます。
| 空間計算量: O(n) | ||
|
|
||
| - 最初に思いついたやり方 | ||
| - 各ノードを配列に一度保存して逆順に再度リンクを張っていく |
There was a problem hiding this comment.
Stackに入れるのでも良いかも。そちらの方が処理はシンプルになりそう。
| node = nodes.get(i); | ||
| node.next = nodes.get(i - 1); | ||
| } | ||
| nodes.get(0).next = null; |
There was a problem hiding this comment.
Listに入れてあげる際(L29のwhile loop内)にnextについてとりあえずnullを入れていても良いかもしれないです。
| return head; | ||
| } | ||
|
|
||
| ListNode prev = null; |
There was a problem hiding this comment.
lastSeenとかはどうでしょうか。Linked List自体にもnext, prev(今回は単方向なのでないですが)があって、結構似たような変数が増えると結構読むのが難しいなという感覚があります
There was a problem hiding this comment.
lastSeen いいですね。
似たような変数が増えると結構読むのが難しい
この観点はなかったのでたしかにと思いました。ありがとうございます。
| node.next = nodes.get(i - 1); | ||
| } | ||
| nodes.get(0).next = null; | ||
| return reverseHead; |
There was a problem hiding this comment.
reverseHead を宣言せず、 return nodes.get(nodes.size() - 1); としてもよいと思いました。
There was a problem hiding this comment.
たしかによく考えたらわざわざ宣言しなくても良いですね
問題
https://leetcode.com/problems/reverse-linked-list/
言語
Java
次に解く問題
Kth Largest Element in a Stream