Skip to content

Conversation

@nittoco
Copy link
Owner

@nittoco nittoco commented Apr 4, 2025

問題文: https://leetcode.com/problems/reverse-linked-list-ii/description/

Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.

- current, next, prevなどの多用は、操作上の問題で、あまり意図が見えないので好みではない(と言いつつ自分もちょこちょこ使っているが)
- odaさんの2番目のコードで書いてみた。区間の左端と、その1個まえのnodeがどこにつながっているかというのだけ変わっているが、実質そんな変わらない気がする
- まあ左端の直前のnodeが、左端のnodeからどんどん奪っていく、という見方をすればちょっと気持ちは違うか
- odaさんのコード見たらinsert_afterだけreturn NoneのNoneがないけど、なんか意図があるのかな
Copy link

Choose a reason for hiding this comment

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

返り値の型の意図が None か Optional[ListNode] かですね。

Copy link
Owner Author

Choose a reason for hiding this comment

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

確かにremove_afterはnodeを返しませんね。(ありがとうございます)

node = node.next
return node

def remove_after(self, node):
Copy link

Choose a reason for hiding this comment

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

remove_afterだと後ろのすべてのnodeを消しそうに感じました。
remove_next、pop_nextとかどうでしょうか。

Copy link
Owner Author

Choose a reason for hiding this comment

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

これ、確かに〜となりました。(ありがとうございます)

reversed_head = before_reversed.next
for i in range(right - left):
removed = self.remove_after(reversed_head)
self.insert_after(before_reversed, removed)
Copy link

Choose a reason for hiding this comment

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

nodeの入れ替えをよく混乱していまうのですが、このように分けると理解しやすいですね

### Step2

- https://discord.com/channels/1084280443945353267/1196498607977799853/1354841302826619021
- torusさんの。なるほど、1 passじゃないとそう解くのか

Choose a reason for hiding this comment

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

逆に私は1-passの方法がパッと浮かびませんでした。

確かnodeの並び順を逆にする、みたいな問題があったのを覚えていて、それと組み合わせて解こう(その問題のフォローアップみたいな位置付け)という感じで考えました。

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.

5 participants