Skip to content

206. Reverse Linked List #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions 206/206.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
## 何も見ずに解く

```python
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
stack = []
node = head
while node:
stack.append(node)
node = node.next
dummy = ListNode(None)
tail = dummy
while stack:
tail.next = stack.pop()
tail = tail.next
tail.next = None
return dummy.next
```

17分かかった(うち13分ぐらいは`tail.next = None`を入れていなかったことが原因のMemory Limit Exceededを解明している時間だった。。)


### Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

recursiveっていうのはこういうことか?

```python
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
def reverse_recursively(head):
if head and head.next:
tail = reverse_recursively(head.next)
tail.next = head
head.next = None
return head
node = head
while node and node.next:
node = node.next
Comment on lines +36 to +38
Copy link

Choose a reason for hiding this comment

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

ここ、もうちょっとなんとかしたいですね。
reverse_recursively がペアで返すなどの方法があると思います。

reverse_recursively(head)
return node
```

## いろいろ調べてみる

https://github.com/cheeseNA/leetcode/pull/11/files
https://github.com/hayashi-ay/leetcode/pull/13/files
https://github.com/5ky7/arai60/pull/8/files
https://github.com/sakupan102/arai60-practice/pull/8/files

stackを使わない解法をしている方が多かった。
おそらく最初の自分の(stackをつかった)解法は、問題文にある"iteratively"にも"recursively"にも分類されない方法っぽい。

再帰のコードは、新しいリストの(その時点の)末端を返すのではなく先頭を返すようにして、ポインタの書き換えは関数の返り値を利用せずにhead側から`head.next.next = head`のような感じでやってしまえば次のようによりシンプルになる。
Copy link

Choose a reason for hiding this comment

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

head.next が最後になることを利用するのは、あんまりスマートではないと私は思います。

再帰にする方法もいくつかありそうです。コメント集を見ておいてください。
https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0#heading=h.x5w37bodndgj

Copy link
Owner Author

Choose a reason for hiding this comment

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

確かに関数がheadとtailを両方返すようにすれば再帰の幅も広がりそうですね!
ありがとうございます。


```python
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
new_head = self.reverseList(head.next)
head.next.next = head
head.next = None
return new_head
```

stackや再帰を使う方法は、stackは単純にスタックを積むので、再帰は関数の呼び出しスタックがたまるので空間計算量がO(n)になる。
その点iterativeな方法は(新しく必要なのは)constantな空間計算量で済むみたいなので、こちらを最終コードにした。
一時保存のための変数名は、nextとすると組み込み関数と被ってちょっと嫌、tmpやtempは何のことを指しているのかわからなくなりそう(実際に自分がこのように書かれたコードを最初に読んで理解に手間取ってしまった)なので、successorとしてみた。

Choose a reason for hiding this comment

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

next_node としても良いと思います。また、previous, next がどの段階での前後関係か分かりにい場合もあるので、previous は reversed_head と書くこともできます。変数名を操作上からつけるパターンと意味からつけるパターンを使い分けられると良さそうです(どこかでコメントされていたと思いますが見つけられませんでした)。

Copy link
Owner Author

@potrue potrue May 9, 2025

Choose a reason for hiding this comment

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

t0hsumi/leetcode#7 (comment)
こちらでしょうか。
たしかに意味を明示的にするなら、current_head_of_reversed, node, initial_successorなどとしても良いかもしれません。
意味的にしたほうがこのコードは全体として何をやっているかがコメントなしにもわかりやすくなりますね。
複雑なロジックになればなるほど意味的に名前を付けたほうがよくなりそうです。
ありがとうございます!

Choose a reason for hiding this comment

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

おそらくそれです。操作の「意味と形式」でしたね。リンク共有ありがとうございます。


## 最終コード

```python
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
current = head
previous = None
while current:
successor = current.next
current.next = previous
previous = current
current = successor
return previous
```
Copy link

Choose a reason for hiding this comment

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

上で指摘されていますが,

return previous

はやや意図が伝わりにくいかもしれません.

successorは個人的にとてもわかりやすくていいなと思いました.

Copy link
Owner Author

Choose a reason for hiding this comment

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

自分も今見たらちょっとわかりにくいかもと思いました、、
変数名を変えるか、あるいはwhileの中に
if not successor: break
を入れてしまうのも手かもしれません。


(かかった時間: 1:32, 0:30, 0:38)