Skip to content

206. Reversed Linked List#8

Open
tNita wants to merge 1 commit into
mainfrom
add/206_reverse_linked_list
Open

206. Reversed Linked List#8
tNita wants to merge 1 commit into
mainfrom
add/206_reverse_linked_list

Conversation

@tNita
Copy link
Copy Markdown
Owner

@tNita tNita commented Dec 27, 2025

return reverse_helper(head)[0]
```

2-1) 実はtailは不要(上でnode.next is Noneの時にnode, nodeと二つ同じものを返しているところに違和感を感じて気づく?)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

不要でも渡したほうが読みやすい気はします。

```
- https://github.com/resumit30minutes/leetcode-arai60-practice/pull/8/files#diff-56cce9af784f5c572f0706e03269e28af28f8aabbface21c32e6199d6400c657
- https://github.com/quinn-sasha/leetcode/pull/7#discussion_r1948355100
- stackを利用する場合でもNodeのまま次へのつながりを切ってstackに積むやり方もあり
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

一応、この問題の出題意図は、LinkedList でお手玉ができますかということかと思うので、これは出題意図には沿っていないだろうと推測します。

def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
reversed_head = None
while head is not None:
reversed_head = ListNode(head.val, reversed_head)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ListNode を作ると結構シンプルに書けるんですね。この場合はもとのノードが残る(新しいノードが増える)ので、そこの良し悪しを意識できると良いと思いました。

return None

node = head
stack = deque()
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

スタックとして使うのであれば list で十分だと思います。一般に、同じ目的に使えるデータ構造が複数ある場合、その中で一番実装が軽いものを選ぶことが多いように思います。

```Python3
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
original_head = head
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

head はリンクトリストの先頭を表すノードのため、変数名を変えたほうが良いかもしれません。ただ、今回は head の位置のノードを逆順のリンクトリストに繋ぎ変え、 head が残りの部分の先頭を表すノードになるため、そのままでも十分通じるかもしれません。

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.

4 participants