Conversation
| def helper(current_node, prev_node): | ||
| if not current_node.next: | ||
| current_node.next = prev_node | ||
| return current_node |
There was a problem hiding this comment.
細かいんですが、if not current_node: にしてreturn prev_nodeにすればcurrent_node.next = prev_nodeの処理がいらないと思うのですが、上記のようにした理由は何かありますか
There was a problem hiding this comment.
覚えてないんですけど、提案していただいた方が良さそうですね。
| prev = head_after_reverse | ||
| while nodes: | ||
| current = nodes.pop() | ||
| prev.next = current |
There was a problem hiding this comment.
質問になってしまい申し訳ないんですが、Linked ListってCycleがあるとエラーになると思うんですが、この部分でエラーが出ないのってなぜなのでしょうか、、、?
Linked Listってドキュメント等ないのでよくわかっておらず、、、
There was a problem hiding this comment.
Linked ListってCycleがあるとエラーになると思うんですが
この部分解像度が粗いと感じたのでもう少し具体的にどういうことか説明してもらって良いですか?
Linked Listってドキュメント等ないのでよくわかっておらず、、、
こちらには転記してなかったのですが、LeetCode上だと以下のように定義されています。
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = nextThere was a problem hiding this comment.
prev.next = currentをすると、ここでprevのnextがcurrentになりますが、この時点ではcurrentのnextがprevになっているため、サイクルが出るはずです。
実際手元でこのポイントでprint(prev)をしてみたところ、'Error - Found cycle in the ListNode'と出ました。
同じようにサイクルが途中で出るコードで、エラーが出て実行完了ができなかったことがあり、もし理由をご存知であればと思いお聞きしました🙇
There was a problem hiding this comment.
それでいうとLinkedListのサイクルがあってもそれ自体はエラーにはならないです。
サイクルがあると処理によっては無限ループしたり、LeetCode側のprintの挙動みたいに無限ループしないように明示的にエラーを表記するようにしていたりします。
There was a problem hiding this comment.
たぶんLeetCodeのListNodeはサイクルがあるとエラーを返すようになってます。サイクルの検知をなくすと無限ループになります。
あと__str__メソッドを定義してあげるとprintした際の表記などを変えることができます。
https://docs.python.org/3/reference/datamodel.html#object.__str__
class MyListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __str__(self):
seen = set()
output = []
current = self
while current:
if current in seen:
return "ERROR!!"
seen.add(current)
output.append(str(current.val))
current = current.next
return f'[{", ".join(output)}]'
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
a = MyListNode(0)
b = MyListNode(1)
a.next = b
b.next = a
print(a)There was a problem hiding this comment.
なるほど、ありがとうございます
表記の仕方まで教えてくださりありがとうございます🙇参考になりました
There was a problem hiding this comment.
さっきnittocoさんの解答確認しましたが、最終結果がサイクルを含むリストになっていたようです。途中結果でサイクルを含む形になっても問題ないです。
もしかしたらユーザ定義のクラスと標準ライブラリのクラスの違いについての理解があやふやなのではないかと感じました。
There was a problem hiding this comment.
ユーザ定義のクラスと標準ライブラリのクラスの違いについての理解があやふやなのではないかと感じました。
ここ、多分全然わかっていないです、、
何かいい資料等ご存知でしょうか🙇
https://leetcode.com/problems/reverse-linked-list/